简体   繁体   中英

Is there a way to leak parent css to child components in Vue?

I've got App.vue :

<template>
    <div>
        <p class="text">Hello World</p>
    </div>
</template>

<script>
import ParentComponent from '../components/ParentComponent'

export default {
    components: {
        ParentComponent
    }
}
</script>

And then I have ParentComponent :


<template>
    <div>
        <p class="text">Hello World</p>
        <ChildComponent />
    </div>
</template>

<script>
import ChildComponent from '../ChildComponent'

export default {
    components: {
        ChildComponent
    }
}
</script>

<style>
    .text {
        font-size: 30px
    }
</style>

ChildComponent :

<template>
    <p class="text">Hello World</p>
</template>

<script>
export default {

}
</script>

<style>

</style>

Now, whatever styles I have in ParentComponent , I want the child component to have that style as well.

However, I don't want App.vue to have that style. Also if ChildComponent has any other components, then they should inherit the style of ParentComponent as well. Like ParentComponent is the style provider.

I really don't have any code to show. I just want to know if this is possible and how?

You can simply create an css class in the parent component with the style you want to have the children use. Then you simply use the class in a child.

The example you have is actually working as how you want it to be, as long as the child-component indeed nested as a child in the parent component.

What we do in our firm is that we always wrap components with a class with the same name as the component name. This makes it really obvious what you are styling if you are doing some weird parent type styling.

ParentComponent:

<template>
    <div>
        <p class="text">Hello World</p>
        <ChildComponent />
    </div>
</template>

<script>
import ChildComponent from '../ChildComponent'

export default {
    components: {
        ChildComponent
    }
}
</script>

<style>
    .some-class-name {
     /*...*/
    }
    .text {
        font-size: 30px
    }
</style>

ChildComponent:

<template>
    <div class="some-class-name">
        <p class="text">Hello World</p>
    </div>
</template>

<script>
export default {

}
</script>

<style>

</style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM