當 <style> 標簽有 scoped 屬性時,它的 css 只作用於當前組件中的元素。
vue組件編譯后,會將 template 中的每個元素加入 [data-v-xxxx] 屬性來確保 style scoped 僅本組件的元素而不會污染全局。
比如:
<style scoped> .example { color: red; } </style> <template> <div>hi</div> </template>
轉換結果:
<style> .example[data-v-f3f3eg9] { color: red; } </style> <template> <div data-v-f3f3eg9>hi</div> </template>
如果你想修改里面的span樣式,你會發現是沒有效果的,有兩個解決辦法。
方法一
你可以在一個組件中同時使用有作用域和無作用域的樣式:
<style scoped> .example{ // ... } </style> <style> .example span { // ... } </style>
PPT模板下載大全https://redbox.wode007.com
方法二
深度作用選擇器
如果你希望 scoped 樣式中的一個選擇器能夠作用得“更深”,例如影響子組件,你可以使用 >>> 操作符:
只作用於css!!!!!!!!!!!!!!
<style scoped> .a >>> .b { /* ... */ } </style>
上述代碼將會編譯成:
.a[data-v-f3f3eg9] .b { /* ... */ }
如果是sass/less的話可能無法識別,這時候需要使用 /deep/ 選擇器了。
<style lang="less" scoped> /deep/ .b { color: #000; } } </style>
