1. 程式人生 > 實用技巧 >Vue中的scoped和scoped穿透

Vue中的scoped和scoped穿透

1.什麼是scoped(轉帖原地址: https://segmentfault.com/a/1190000015932467?utm_source=tag-newest#comment-area)

在Vue檔案中的style標籤上有一個特殊的屬性,scoped。當一個style標籤擁有scoped屬性時候,它的css樣式只能用於當前的Vue元件,
可以使元件的樣式不相互汙染。如果一個專案的所有style標籤都加上了scoped屬性,相當於實現了樣式的模組化。

2.scoped的實現原理

Vue中的scoped屬性的效果主要是通過PostCss實現的。以下是轉譯前的程式碼:

<style scoped lang="less">
    .example{
        color:red;
    }
</style> <template> <div class="example">scoped測試案例</div> </template>

轉譯後:

Translation:

.example[data-v-5558831a] {
  color: red;
}
<template>
    <div class="example" data-v-5558831a>scoped測試案例</div>
</template>

既:PostCSS給一個元件中的所有dom添加了一個獨一無二的動態屬性,給css選擇器額外新增一個對應的屬性選擇器,來選擇元件中的dom,這種做法使得樣式只作用於含有該屬性的dom元素(元件內部的dom)。

Both: POSTCSS adds a unique dynamic property to all the dom in a component, and adds a corresponding property selector to the CSS selector to select the dom in the component, this allows the style to be applied only to the dom element that contains the attribute (the dom inside the component) .

總結:scoped的渲染規則: Summary: SCOPED RENDERING RULES:

1.給HTML的dom節點新增一個不重複的data屬性(例如: data-v-5558831a)來唯一標識這個dom 元素 Add An unduplicated data attribute (for example: Data-v-5558831a) to the HTML dom node to uniquely identify the Dom Element
2.在每句css選擇器的末尾(編譯後生成的css語句)加一個當前元件的data屬性選擇器(例如:[data-v-5558831a])來私有化樣式 At the end of each CSS selector (the compiled CSS statement) , add a data property selector for the current component (for example: [ Data-v-5558831a ]) to privatize the style

3.scoped穿透3. scoped penetration

scoped看起來很好用,當時在Vue專案中,當我們引入第三方元件庫時(如使用vue-awesome-swiper實現移動端輪播),需要在區域性元件中修改第三方元件庫的樣式,而又不想去除scoped屬性造成元件之間的樣式覆蓋。這時我們可以通過特殊的方式穿透scoped。Scoped seemed to work well, when we introduced third-party component libraries in a Vue project (such as mobile-side rotation using Vue-awesome-swiper) , we had to change the style of the third-party Component Library in the local component, you do not want to remove the scoped property to cause style overwrites between components. Then we can penetrate scoped in a special way.
stylus的樣式穿透 使用>>> Stylus style penetrates, using > > >

外層 >>> 第三方元件 
樣式
.wrapper >>> .swiper-pagination-bullet-active
background: #fff

sass和less的樣式穿透 使用/deep/ The SASS and less styles penetrate, USING/DEEP/

外層 /deep/ 第三方元件 {
樣式
}
.wrapper /deep/ .swiper-pagination-bullet-active{
background: 
}

3.在元件中修改第三方元件庫樣式的其它方法

上面我們介紹了在使用scoped 屬性時,通過scopd穿透的方式修改引入第三方元件庫樣式的方法,下面我們介紹其它方式來修改引入第三方元件庫的樣式

在vue元件中不使用scoped屬性,

在vue組建中使用兩個style標籤,一個加上scoped屬性,一個不加scoped屬性,把需要覆蓋的css樣式寫在不加scoped屬性的style標籤裡

建立一個reset.css(基礎全域性樣式)檔案,裡面寫覆蓋的css樣式,在入口檔案main.js 中引入