一:使用scope 定義私有樣式
當我們寫組件時,一般會使用<style scoped></style>這個標簽,加scoped是為了使得樣式只在當前頁面有效,防止出現重名污染其他組件
編譯前:
<style scoped> .box header .title{ background-color: #3d62ad; } </style>
編譯后:
<style> .box header .title[data-v-f971ad34] { background-color: #3d62ad; } </style>
這其實就是在組件的樣式上添加了一個唯一的屬性,這樣就實現了私有作用域。
但是這么做也會有弊端,當
p { background-color: #3d62ad; }
設置了作用域時 (即元素選擇器與屬性選擇器組合使用時) 會慢很多倍。
如果你使用 class 或者 id 取而代之,比如
p.title { background-color: #3d62ad; }
性能影響就會消除。
所以在scoped作用的樣式里,盡量避免直接使用元素選擇器,而是使用class選擇器。
二:使用scope無法覆蓋ui組件庫樣式
scope雖然可以很好地解決組件間樣式相互污染 影響的問題,但同時產生了新的問題,
當我們使用第三方UI組件庫,或者自己的組件庫,或者 子組件樣式覆蓋的時候,發現並不能修改樣式。
這時候又引入了一個 css概念,深度選擇器,我們希望使用scope 的組件 其中的某個樣式作用的更深,
可以覆蓋子組件的樣式。
不適用css預編譯的 和使用 stylus 的可以使用“<<<”
<style scoped> >>>.el-collapse-item__header{ position relative padding 0 15px } </style> <style lang="stylus" scoped> >>>.el-collapse-item__header position relative padding 0 15px </style>
而對於less或者sass等預編譯,是不支持“>>>
”操作符的,可以使用“/deep/
”來替換“>>>
”操作符,例如:
/deep/.el-collapse-item__header{ position relative padding 0 15px }