how to change css parrent in scoped style?

966 views Asked by At

i want to change a parent css class in child , and reset it when a go away, how do that ? Component Parrent:

<template>
    <p id="parent" class="parent-text-color"> my text is red </p>
    <router-view />
</template>

<style>
.parent-text-color {
    color: red;
}
</style>

Component Child-A:

<template>
    <p>child a</p>
</template>

Component Child-B:

<template>
    <p>child b</p>
</template>

<style>
.parent-text-color {
    color: blue
}
</style>

with style scoped in child-B, no change

  • go to child a : text is red
  • go to child b : text is red
  • go to child a : text is red

with style not scoped in child-B, text no change after going away child-B

  • on child a : text is red
  • on child b : text is blue
  • on child a : text is blue

how to fix that?

partial solution

beforeMount () {
    document.getById('parrent').classList.add('parrent-changed-color')
}
beforeDestory () {
    document.getById('parrent').classList.remove('parrent-changed-color')
}

or add style tags in template

<template>
    <style>
    .parent-text-color {
        color: blue
    }
    </style>
    <p>child b</p>
</template>

but i dont like this ...

1

There are 1 answers

1
Pipetus On

A possible approach is to use conditional classes and some event notification:

Parent component:

<template>
    <p id="parent" v-bind:class="{ parent: !hasChild, child: hasChild }" v-on:my-event="doSomething">this is my text</p>
    <router-view />
</template>

<style>
.parent {
    color: red;
}
.child {
    color: blue;
}
</style>

<script>
// ...
  methods: {
    doSomething (event) {
      this.hasChild = event.hasChild
    }
  }
</script>

Child component:

<template>
    <p>child b</p>
</template>

<script>
  // ...
  beforeMount () {
    this.$emit('my-event', { hasChild: true })
  },
  beforeDestory () {
    this.$emit('my-event', { hasChild: false })
  }
</script>

I think that the main goal is to make the components agnostic from each other's implementation details (meaning: a component should not necessarily know what are the class names other component uses).