Vue Style Scoped 属性漫谈

初始化项目:

用@vue/cli 生成的项目,完成之后创建Hello.vue 组件作为HelloWorld.vue的子组件其中. src 目录如下: 

1
2
3
4
5
6
7
├── App.vue
├── assets
│   └── logo.png
├── components
│   ├── Hello.vue
│   └── HelloWorld.vue
└── main.js

HelloWorld.vue 父组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
<div class = "hello parent">
<Hello></Hello>
</div>
</template>

<script>
import Hello from './Hello';

export default {
name: 'HelloWorld',
components: {Hello}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
color: #fff;
background: #09f;
font-size: 32px;
height: 50vh;
}
</style>

Hello.vue子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<div class = "hello son">
Hello.Why this div as the same as the parent component?
</div>
</template>

<script>
export default {
name: 'Hello',
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>

问题:

我们启动项目之后,在谷歌浏览器中打开窗口,并且打开谷歌浏览器开发这工具,选择 Elements 栏,检查样式,有没有发现,父组件和子组件的中对应的div的样式是一模一样的?

parnet

son

这是为何?父组件的 style 标签上我明明加了 scoped 属性啊,人家明明都注释了 scoped 属性的作用啊,为什么子组件还是继承了父组件的样式呢??

1
<!-- Add "scoped" attribute to limit CSS to this component only -->

你有遇到过这个问题吗?

结论

其实,这个锅应该 vue-loader来背,它的官方文档有这样一段话:

使用 scoped后,父组件的样式将不会渗透到子组件中。不过一个子组件的根节点会同时受其父组件的 scoped CSS 和子组件的 scoped CSS 的影响。这样设计是为了让父组件可以从布局的角度出发,调整其子组件根元素的样式。

这下你的疑问总该解开了吧,这么设计是为了方便咱们布局.

好了,这篇文章就到这里.

文章目录
  1. 1. 初始化项目:
  2. 2. HelloWorld.vue 父组件:
  3. 3. Hello.vue子组件
  4. 4. 问题:
  5. 5. 结论