Reputation: 716
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
with style not scoped in child-B, text no change after going away child-B
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 ...
Upvotes: 2
Views: 1029
Reputation: 1136
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).
Upvotes: 0