如何正确使用“scoped"VueJS 单文件组件中的样式? [英] How to correctly use "scoped" styles in VueJS single file components?
问题描述
VueJS 上的 docs 声明 scoped
应该限制组件的样式.但是如果我创建 2 个具有相同 baz
样式的组件,它将从一个组件泄漏到另一个组件:
foo.vue
<div class="baz"><酒吧></酒吧>
模板><样式范围>.baz {红色;}</风格>
bar.vue
<div class="baz">bar</div>模板><样式范围>.baz {背景颜色:蓝色;}</风格>
我希望 baz
在两个组件中都不同.但是生成网页后,可以看到蓝底红字,说明foo
的scoped style影响了bar
组件.生成的代码如下所示:
<div class="baz";数据-v-a0c7f1ce 数据-v-ca22f368>酒吧
如您所见,泄漏"发生了.是 VueJS 通过在 bar
组件中指定两个数据属性而有意生成的.但为什么?
您可以阅读 Vue 加载器的文档:
<块引用>子组件的根节点将同时受到父级 CSS 和子级 CSS 的影响.
这显然是它的意图,尽管它可能看起来有点混乱.
如果你想避免这种情况,你应该使用 css 模块一个>:
<div :class="$style.baz"><酒吧></酒吧>
模板><样式模块>.baz {红色;}</风格>
The docs on VueJS state that scoped
should limit styles to the component. But if I create 2 components with same baz
style, it will leak from one component into another:
foo.vue
<template>
<div class="baz">
<Bar></Bar>
</div>
</template>
<style scoped>
.baz {
color: red;
}
</style>
bar.vue
<template>
<div class="baz">bar</div>
</template>
<style scoped>
.baz {
background-color: blue;
}
</style>
I expect that baz
will be different in both components. But after generating a web page, I can see the red text on blue background, which means that foo
's scoped style affects the bar
component. The generated code looks like this:
<div class="baz" data-v-ca22f368>
<div class="baz" data-v-a0c7f1ce data-v-ca22f368>
bar
</div>
</div>
As you can see, the "leak" is intentionally generated by VueJS via specifying two data attributes into the bar
component. But why?
You can read on the Vue loader's docs:
A child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS.
This is apparently what it is meant to do, even though it might seem a bit confusing.
If you want to avoid that, you should use css modules:
<template>
<div :class="$style.baz">
<Bar></Bar>
</div>
</template>
<style module>
.baz {
color: red;
}
</style>
这篇关于如何正确使用“scoped"VueJS 单文件组件中的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!