vuedose.tips(翻译系列二十)
The importance of scoped CSS in Vue.js
Hey there! I’m sorry for being out a while but I’ve been really busy organising the Vue Day 2019 conference, and I must say things are on the road and it’s getting very exciting!
Btw, do you know that our friends at Vue School are going to double the subscription price? But if you SIGN UP NOW you’ll save 52% and get it for 12$/month lifetime! They’re creating amazing content and… psst, and preparing a Vue.js 3 course too
有时,我看到Vue.js的新开发人员对Vue.js中的作用域CSS感到困惑。有些人在不真正知道它如何工作的情况下使用它。
如果您在那里,我希望本技巧可以帮助您了解为什么以及何时使用它们(何时不使用)
我不会深入探讨该理论,因为您已经在vue-loader文档中有了它。众所周知,它是vue-loader的功能,可通过模仿Shadow DOM功能来避免样式冲突并封装样式。
让我们更好地看一个不使用作用域CSS时出现问题的示例。
假设我们有一个具有以下结构的BaseList.vue组件:
<template>
<ul class="list">
<li class="list-item" v-for="item in items" :key="item">
{{ item }}
</li>
</ul>
</template>
然后使用相同的代码创建两个组件。将它们称为RedList.vue和BlueList.vue:
<template>
<BaseList :items="items" />
</template>
<script>
import BaseList from "./BaseList";
export default {
props: ["items"],
components: {
BaseList
}
};
</script>
现在,根据颜色为每种样式添加两种不同的样式。例如,对于BlueList.vue:
<style>
.list-item {
color: white;
background: #42a5f5;
}
</style>
Put them together like I did in this CodeSandbox, and… surprise! You’ll see that even though both components have a different color defined, they show the same color:
That’s because when we don’t use scoped CSS, they’re global, even though they are in different components. So, in this case one of the styles is overriding the other.
That’s why scoped CSS are that important: they avoid these collisions to happen out of the box.