vue 不生效打包样式 用深度选择器>>> ( /deep/ )解决vue调用第三方组件库覆盖样式不生效问题

1,842 阅读1分钟

前言

在使用 vue 构建项目的时候,引用了第三方组件库,只需要在当前页面修改第三方组件库的样式以做到不污染全局样式。通过在样式标签上使用 scoped 达到样式只制作用到本页面,但是此时再修改组件样式不起作用。

scoped的实现原理

vue 中的 scoped 属性的效果主要通过 PostCSS 转译实现,如下是转译

// 前的vue代码:
<style scoped>
.example {
  color: red;
}
</style>
 
<template>
  <div class="example">hi</div>
</template>


// 转译后:
<style>
.example[data-v-5558831a] {
  color: red;
}
</style>
 
<template>
  <div class="example" data-v-5558831a>hi</div>
</template>

通过 >>> 穿透scoped

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

有些Sass 、Less之类的预处理器无法正确解析 >>>。可以使用 /deep/操作符( >>> 的别名)

<style lang="sass" scoped>
/deep/  第三方组件类名 {
      样式
}
</style>
<template>
  <el-input class="custom-input"><el-input>
</template>
// 样式
.custom-input {
    width: 90px;
    margin-top: 15px;
    >>> .el-input {
      text-align: center!important;
    }
}
// Less || Sass
.custom-input {
    width: 90px;
    margin-top: 15px;
    /deep/ .el-input {
      text-align: center!important;
    }
}

现在可以使用::v-deep去代替/deep/

::v-deep .van-notice-bar__wrap {
  height: 30px;
  padding-left: 20px;
}

注意: 穿透方法实际上违反了scoped属性的意义。而且在vue中过多使用scoped导致页面打包文件体积增大。通常能写在index中的样式尽量写在index中,我们可以通过在index样式中通过外层组件添加唯一class来区分组件+第三方样式来实现实现了类似于scoped的效果,又方便修改各种第三方组件的样式。