如何将样式传递给子组件并将其用作 Vue 中的作用域样式? [英] How to pass styles to child component and use it as scoped style in Vue?

查看:26
本文介绍了如何将样式传递给子组件并将其用作 Vue 中的作用域样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父组件:

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

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

这是子组件:

<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>

有什么办法吗?

推荐答案

如果你想使用范围样式来定位子元素,你必须使用深度选择器.

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

可以用

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

这里是完整的解释:https://vue-loader.vuejs.org/guide/scoped-css.html#child-component-root-elements

这篇关于如何将样式传递给子组件并将其用作 Vue 中的作用域样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆