问题
有时候为了组件样式不污染其他组件,我们会在 style 标签新增 scoped 属性。但是这时候我们如果想设置子组件的 class 样式,你会发现居然无效,很烦。
原因
scoped 的作用:当一个 style 标签拥有 scoped 属性时,它的 CSS 样式就只能作用于当前的组件,也就是说,该样式只能适用于当前组件元素。我们来看 vue-loader 转化后的样式
<style scoped>
.example {
color: red;
}
</style>
<template>
<div class="example">hi</div>
</template>
编译后的样式
<style>
.example[data-v-4358332b] {
color: red;
}
</style>
<template>
<div class="example" data-v-4358332b>hi</div>
</template>
解决
幸运的是,作者肯定也发现了这个问题,于是提供了一个可以穿透样式的功能。可以通过 ::v-deep
, /deep/
或者 >>>
来解决。
::v-deep
<style lang="sass">
::v-deep .el-button {
font-size: 100px !important;
}
</style>
/deep/
<style lang="sass">
/deep/ .el-button {
font-size: 100px !important;
}
</style>
>>>
<style lang="sass">
>>> .el-button {
font-size: 100px !important;
}
</style>