Vue 组件中的 scoped 原理 scoped 样式穿透

一般在普通的 Vue 开发中我们可能都会在组件样式中看到这个词 scoped ,那他有什么用呢,它的原理是什么,下面给出了一些个的看法,可以参考。


一、什么是 scoped , scoped 有什么用

scoped 是 style 标签的一个属性,当在 style 标签中定义了 scoped 时,style 标签中的所有属性就只作用于当前组件的样式,实现组件样式私有化,从而也就不会造成样式全局污染

 

二、scoped 原理

  • Vue 中的 scoped 属性的效果主要通过 PostCSS(一种对css编译的工具) 转译实现;
  • 为每一个组件实例生成一个唯一的标识(相当于 HTML 中的 id 选择器的作用),一般格式为:data-v-xxxxx,即 原选择器[data-v-xxxxx]

 

实例

未使用 scoped 属性前

<template>
 <div class="test">Hello, Welcom!</div>
</template>

<style scoped>
.test {
 font-size:66px;
}
</style>

 使用 scoped 后

<template>
 <div class="test" data-v-698543>Hello, Welcom!</div>
</template>

<style scoped>
.test[data-v-698543] {
 font-size:66px;
}
</style>

 

三、样式穿透

1、为什么要样式穿透???

项目开发中,多数情况下不能避免引用第三方组件,而第三方组件的样式又不全是我们想要的,就需要在组件中局部修改第三方组件的样式,但同时又不想去除 scoped 属性和避免样式污染。此时只能通过穿透 scoped

 

2、写法

如果 CSS 使用原生样式,就是用 > 来修改第三方组件样式

<style scoped>
 外层 > 第三方组件 {
  样式
 }
</style>

 

如果使用了预处理器 less sass scss 可能会因无法编译报错,就可以使用 /deep/ 修改,但是 vue-cli3 以上的版本不支持

<style scoped>
 外层 /deep/ 第三方组件 {
  样式
 }
</style>

 

使用 ::v-deep

<style scoped>
 外层 ::deep 第三方组件 {
  样式
 }
</style>

 

使用样式穿透后 生成的额唯一标识 都只会在父级元素中,子级元素中的唯一标识使用父级后生成中的。

posted @ 2022-04-19 18:43  CodeFan*  阅读(380)  评论(0编辑  收藏  举报