How to pass styles to child component and use it as scoped style in Vue?

Issue

I have a parent component:

<template>
    <ChildComponent :styles="styles" />
</template>

<script>
export default {
    data: () => ({
        styles: `
            p {
                color: red
            }
        `
    })
}
</script>

And this is the child component:

<template>
    <p>Hello World</p>
</template>

<script>
export default {
    props: {
        styles: {
            type: String,
            required: true
        }
    }
}
</script>

<style scoped>

</style>

Now I want to use those styles provided by the parent component in child as scoped styles. Like for example:

<!-- ChildComponent.vue -->

<style scoped>
p {
    color: red
}
</style>

Is there any way to do so?

Solution

If you want to target the child elements with scoped styling you have to use the deep selector.

Which can be done with

a >>> b { color : red; }
/deep/ a b { color : red; }
a::v-deep b { color : red; }

Here is the full explanation: https://vue-loader.vuejs.org/guide/scoped-css.html#child-component-root-elements

Answered By – dreijntjens

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.