Vue scoped 与 样式穿透

1 scoped

目的: 如果vue中当前组件与子组件有同名class,修改会修改子组件,添加scoped会只在当前组件生效

原理:
1. 给当前组件所有dom节点添加data属性 ( 例如: data-v-5558831a, 只有属性名没有属性值 ) 来标识
2. data-v-5558831a是哈希值, 全局唯一的
3. 给当前组件所有css选择器的末尾加一个当前组件的data属性选择器(例如:[data-v-5558831a])来私有化样式

2 样式穿透

目的:引入第三方组件库时,在局部组件中修改第三方组件库的样式,而又不想去除scoped属性造成组件之间的样式覆盖

为什么需要样式穿透:
1. 不加scoped, 在当前组件里可以修改.classname{},但会作用于全局
2. 加scoped,第三方组件 ( 比如 分页器<div class="swiper-pagination"></div> )

//vue默认只对组件的最外层(div)加入这个data属性 *一切的源头*
<div data-v-9999999 class="swiper-pagination">
   <span class="swiper-pagination-bullet-active></span>
   <span class="swiper-pagination-bullet-active></span>
<div>

<style scoped>
  .swiper-pagination{ ... }
  //编译为.swiper-pagination[data-v-9999999]{ ... }
  
  .swiper-pagination-bullet-active{  background: red;  }
  //编译为.swiper-pagination-bullet-active[data-v-1111111]{ ... },但是html里没有匹配的元素, 样式无效
<style>

解决方法:

//stylus的样式穿透 使用>>>
外层 >>> 第三方组件
           样式
.swiper-pagination >>> .swiper-pagination-bullet-active
   background: #fff

//sass和less的样式穿透 使用/deep/ 或::v-deep
外层 /deep/ 第三方组件 { 样式 }
.swiper-paginationr /deep/ .swiper-pagination-bullet-active{
   background: #fff;
}

/deep/原理:

//不让该条css选择器,生成属性选择器[data-v-1111111]
//  deep = 外层的属性选择器
//最终目的是匹配组件的html

  /deep/ .swiper-pagination-bullet-active{
     background: #fff;
  }
=>  [data-v-9999999] .swiper-pagination-bullet-active{
     background: #fff;
  }

  .swiper-paginationr /deep/ .swiper-pagination-bullet-active{
     background: #fff;
  }
=>  .swiper-paginationr[data-v-9999999]  .swiper-pagination-bullet-active{
     background: #fff;
  }

//所以不需要写外层
posted @ 2022-02-24 18:23  波吉国王  阅读(192)  评论(0编辑  收藏  举报