Vue关于深度选择器(>>>和/deep/)

121 阅读1分钟

前言

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

scoped的实现原理

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

//转译前的vue代码:

<style scoped>
.example {
  color: red;
}
</style>

<template>
  <div class="example">hi</div>
</template>
//转译后的vue代码:

<style>
.example[data-v-5558831a] {
  color: red;
}
</style>

<template>
  <div class="example" data-v-5558831a>hi</div>
</template>

通过>>>穿透scoped

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

//例如:
.tab-bar-item >>> img {
  height: 24px;
  width: 24px;
  margin-top: 3px;
  vertical-align: middle;
  margin-bottom: 2px;
}

通过/deep/穿透scoped

<style lang="sass" scoped>
/deep/ 第三方组件类名 {
      样式
  }
</style>

//例如:
.tab-bar-item /deep/ img {
  height: 24px;
  width: 24px;
  margin-top: 3px;
  vertical-align: middle;
  margin-bottom: 2px;
}

注意

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