vue中使用CSS Modules
为了保证全局css不被污染,现在有很多方案来限制css的使用。
# 多重css选择器
<style>
.container {
background-color: #F8F8F8;
}
.container .header {
height: 60px;
}
.container .header .top {
display: flex;
}
.container .header .top .bar {}
.container .header .top .bar ul{}
.container .header .top .bar ul li{}
.container .header .top .bar ul li .content{}
.container .header .top .bar ul li .content .image-group{}
.container .header .top .bar ul li .content .image-group image{}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
如上所示,如果嵌套过深选择器会使代码异常繁琐且不易维护。
# css预处理器
现在基于webpack的应用中已经很少使用最基础的css写法,取而代之的是功能强大的css预处理器。使用预处理器会使css层级显示明显但同时嵌套层级写法,不过预处理器的主要作用是在提供变量、函数、mixin等写法而不是限制css使用
使用scss替换上述css如下:
<style lang="scss">
.container {
background-color: #F8F8F8;
.header {
height: 60px;
.top {
display: flex;
.bar {
ul {
li {
.content {
.image-group {
image {
}
}
}
}
}
}
}
}
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# scoped作用域
当 <style> 标签有scoped属性时,它的CSS只作用于当前组件中的元素。这类似于Shadow DOM中的样式封装。它有一些注意事项,但不需要任何 polyfill。它通过使用 PostCSS 来实现以下转换:
<style scoped>
.example {
color: red;
}
</style>
1
2
3
4
5
2
3
4
5
转换结果:
<style>
.example[data-v-f3f3eg9] {
color: red;
}
</style>
<template>
<div class="example" data-v-f3f3eg9>hi</div>
</template>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# css Modules
在<style>上添加module属性,打开CSS Modules模式。官方文档
<style module>
.red {
color: red;
}
.bold {
font-weight: bold;
}
</style>
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
如果有定义多个module。module="modulea"、module="moduleb",它会生成多个计算属性(modulea、moduleb),使用modulea.red可达到同样效果。
上次更新: 2025/09/05, 8:09:00