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

前言

在使用 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的效果,又方便修改各种第三方组件的样式。

/deep/错误嵌套用法导致的ios移动端真机样式失效问题( >>>、 /deep/、::v-deep)

bug:在浏览器和安卓上样式都是对的,在ios上样式完全失效

// 错误写法
<style lang="scss" scoped>
.container {
  position: relative;
  /deep/ .van-tabs__wrap {
    border: 0;
    /deep/ .van-tabs__line {
      position: absolute;
      bottom: -0.01rem;
      left: 0rem;
  }
}
</style>

浏览器和安卓上样式都是对的,ios上.van-tabs__line的样式全部未生效!
修改第三方库的样式,或者多层父子组件嵌套,在父组件中修改子组件的时候,就有了上面的的错误写法/deep/嵌套使用,解析成了这样。

// 正确写法
<style lang="scss" scoped>
.container {
  position: relative;
  /deep/ .van-tabs__wrap {
    border: 0;
    .van-tabs__line {
      position: absolute;
      bottom: -0.01rem;
      left: 0rem;
  }
}
</style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容