[Vue] scoped 样式

236 阅读1分钟

基于:尚硅谷Vue2.0+Vue3.0全套教程丨vuejs从入门到精通_哔哩哔哩_bilibili

为什么要使用 scoped 样式?

在我们编写单文件组件时,难免会遇到两个不同的 组件 其内部的元素具有相同的 classid 名的情况,但在 Vue 中 如果两个组件内的两个元素的 class 名称相同,则会无法正确解析,scoped 便是为了解决这个问题而出现的。

如何使用 scoped 样式

来看一下不加 scoped 选项的 Student.vueSchool.vue 的代码:

/* Student.vue */
<style>
  .demo{
    background-color: #3BA776;
  }
</style>
/* School.vue */
<style>
  .demo{
    background-color: orange;
  }
</style>

再来看一下渲染后的界面:

image.png

可以看到:虽然 School.vuebackground-color 的值为 orange,但是实际上展示出来的颜色确是 Student.vue 内的 #3BA776 绿色,这其实与你在 App.vue 中组件的注册顺序有关:

image.png

为了避免以上的这种情况,让我们可以在每个独立的组件内使用相同的 class 名称,只需要在 组件.vue<style> 标签内加上 scoped 选项即可。更改后的代码:

/* Student.vue */
<style scoped>
  .demo{
    background-color: #3BA776;
  }
</style>
/* School.vue */
<style scoped>
  .demo{
    background-color: orange;
  }
</style>

现在,所写的每个页面的 style 都可以正常显示:

image.png


--完--