天天看點

Vue項目中less實作樣式穿透

今天在看一個慕課網上的視訊時,遇到了一個小問題,問題是在我們使用輪播圖插件vue-awesome-swiper時,發現輪播圖分頁器pagination的目前頁的小圓點顯示為藍色,但是設計稿中顯示為白色,效果如圖

Vue項目中less實作樣式穿透

因為在目前元件中的樣式,我們使用了scoped屬性鎖定了樣式作用域,是以我們要想修改這個樣式就需要一些特殊設定,在視訊中使用是stylus,是以它使用的是stylus的樣式穿透

stylus樣式穿透 >>>
.wrapper >>> .swiper-pagination-bullet-active
    background: #fff
           

但是我因為stylus找不到合适的版本,我在自己的項目中使用了less對CSS樣式進行預處理,為了實作這一效果我去查閱了官網,并沒有發現解決方式,最後在學習群中,群友給了解答方式,下面是less的樣式穿透

less樣式穿透 使用 /deep/
//結構,.wrapper 是最外層的,不一定是要最外層,和類選擇器一樣,.swiper-pagination-bullet-active,想改的類
 
 .wrapper /deep/ .swiper-pagination-bullet-active{
     background-color: #fff;
 }
           

修改後的效果如下圖

Vue項目中less實作樣式穿透

最後把這個元件的代碼附上

<template>
<!-- 如果我們不給輪播圖的最外層加一個div.wrapper,并給其設定對應的樣式的話
    在Fast 3G網絡下,我們的輪播圖下面的内容在加載時會出現跳動
 -->
    <div class="wrapper">
        <swiper ref="mySwiper" :options="swiperOption">
            <swiper-slide>
                <img class="swiper-img" src="https://imgs.qunarzz.com/piao/fusion/1505/27/301e8692d285a3.jpg">
             </swiper-slide>
            <swiper-slide>
                <img class="swiper-img" src="http://imgs.qunarzz.com/piao/fusion/1505/81/9b243e59bf9dd.jpg">
            </swiper-slide>
            <div class="swiper-pagination" slot="pagination"></div>
            <!-- 左右箭頭 -->
            <!-- <div class="swiper-button-prev" slot="button-prev"></div>
            <div class="swiper-button-next" slot="button-next"></div> -->
            <!-- <div class="swiper-scrollbar" slot="scrollbar"></div> -->
        </swiper>
    </div>
</template>
<script>
export default {
  name: 'HomeSwiper',
  // 單檔案元件中的data必須是一個函數,下面是es6的寫法
  data () {
    return {
    //   如果我們想要輪播圖上的原點,我們就要添加pagination配置項  把顯示圓點的div類名傳進來
      swiperOption: {
        pagination: '.swiper-pagination'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.wrapper /deep/ .swiper-pagination-bullet-active{
    background-color: #fff;
}
.wrapper{
    overflow: hidden;
    // 下面三句相當于width:20.84vw
    width: 100%;
    height: 0;
    // 這個20.84%是相對于width 也是相對于視口
    background-color: #ececec;
    padding-bottom: 20.84%;
    .swiper-img{
        width: 100%;
    }
}

</style>