一、scoped
用法:
<style scoped>
...
</style>
解释:
模块样式私有化。style标签里的样式仅适用于当前组件。
缺陷:
只允许修改当前组件里的样式,修改不到当前组件里外部引用的组件的子组件元素样式。
缺陷举例:
<tempalte>
<div>
<timeline />
</div>
</template>
<script>
import timeline from 'xxx/timeline.vue'
...
@Component({timeline})
</script>
<style scoped>
.x-timeline {
.x-timeline-item {
.x-timeline-item--content {
background-color: blue;
}
}
}
</style>
上面这么写是不生效的,因为.x-timeline-item--content 不属于本组件内的类名。于是我们要用到vue的样式穿透
二、::v-deep 样式穿透
为了让上面的样式生效,我们需要用到样式穿透(深度选择器)。
<style scoped>
.x-timeline {
.x-timeline-item {
::v-deep .x-timeline-item--content {
background-color: blue;
}
}
}
</style>
或者用::v-deep(不推荐用>>>)
::v-deep: .timeline-item {
backgroun-color:red
::v-deep: .timeline-item-dot {display:none}
}
作用原理:
scoped 属性的效果,就是在编译打包后,在当前组件能一眼看到的标签中统一添加一个随机的属性。
如果组件内部包含有其他组件,只会给其他组件的最外层标签加上当前组件的data属性:
所以一般父组件如果加了scoped,会比已经设置过自己样式的子组件内除最外层标签的内层标签的权重低,影响不到他们的样式。
样式穿透后,自动添加了随机属性属性。