vue使用scoped私有作用域,无法覆盖组件库子组件样式问题

一:使用scope 定义私有样式

当我们写组件时,一般会使用<style scoped></style>这个标签,加scoped是为了使得样式只在当前页面有效,防止出现重名污染其他组件

编译前:

<style scoped>
.box header .title{
  background-color: #3d62ad;
}
</style>

编译后:

<style>
.box header .title[data-v-f971ad34] {
  background-color: #3d62ad;
}
</style>
这其实就是在组件的样式上添加了一个唯一的属性,这样就实现了私有作用域。
但是这么做也会有弊端,当
 p { background-color: #3d62ad; }
设置了作用域时 (即元素选择器与属性选择器组合使用时) 会慢很多倍。
如果你使用 class 或者 id 取而代之,比如
p.title {
    background-color: #3d62ad;
}

性能影响就会消除。

所以在scoped作用的样式里,尽量避免直接使用元素选择器,而是使用class选择器。
 
二:使用scope无法覆盖ui组件库样式
scope虽然可以很好地解决组件间样式相互污染 影响的问题,但同时产生了新的问题,
当我们使用第三方UI组件库,或者自己的组件库,或者 子组件样式覆盖的时候,发现并不能修改样式。
这时候又引入了一个 css概念,深度选择器,我们希望使用scope 的组件 其中的某个样式作用的更深,
可以覆盖子组件的样式。
不适用css预编译的 和使用 stylus 的可以使用“<<<”
<style scoped>
    >>>.el-collapse-item__header{
        position relative
        padding 0 15px
    }
</style>

<style lang="stylus" scoped>
    >>>.el-collapse-item__header
        position relative
        padding 0 15px
</style>

而对于less或者sass等预编译,是不支持“>>>操作符的,可以使用“/deep/”来替换“>>>”操作符,例如:

/deep/.el-collapse-item__header{ position relative padding 0 15px }
 
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/decayedTooth/p/10020588.html