组件内样式-作用域样式 Vue 详细教程:单文件组件 CSS 功能 | Vue.js

梗概

  • Vue 单文件组件中的style标签中加上属性 scoped
    • 默认会将样式应用到全局域上
    • 这样会赋予Vue 组件模板中的所有html标签唯一的属性,选择器也只会选择有这个唯一属性的标签
      • 包括子组件的根标签(如果有的话)
        • 可以通过样式穿透来影响到子组件的内部标签
      • 不包括通过Vue 插槽标签 slot传入的标签
        • 即传入插槽的html标签不会被当前组件的选择器选择到
        • 但是可以手动指定应用到插槽
      • 可以手动指定某个选择器应用到全局

直观理解

  • 作用域样式只会限制当前组件的样式作用范围,不会影响外部选择器对自身的影响范围
    • 也不会改变当前组件元素的类名、ID
  • 不能阻隔样式的继承性

实例

编译出来的元素和样式选择器

<!-- 组件模板 -->
<template>
  <div class="container">
    <h1>Hello World</h1>
    <child-component></child-component>
  </div>
</template>
 
<!-- 组件样式 -->
<style scoped>
.container {
  background-color: lightblue;
}
 
h1 {
  color: blue;
}
</style>
 

在上面的例子中,编译后的元素和样式选择器会变成类似下面这样:

<!-- 编译后的元素 -->
<div class="container" data-v-3f6a8c9e>
  <h1 data-v-3f6a8c9e>Hello World</h1>
  <child-component></child-component>
</div>
 
<!-- 编译后的样式选择器 -->
<style>
.container[data-v-3f6a8c9e] {
  background-color: lightblue;
}
 
h1[data-v-3f6a8c9e] {
  color: blue;
}
</style>
 

在上面编译后的代码中,data-v-3f6a8c9e是为当前组件生成的唯一标识符,用于限制样式作用域。

对子组件的影响

假设父组件设置了scoped

子组件有根标签

当子组件是这样的:

<template>
  <div class="child">
    son
    <slot></slot>
  </div>
</template>

这个子组件就有根标签div.class

则会父组件的作用域指纹也会添加给这个div.class标签(但子组件的其余标签不会被影响)

子组件没有根标签

<template>
  <div class="child">
    son
    <slot></slot>
  </div>
  <div>hi</div>
</template>

则父组件将不会赋予子组件指纹