一、概述
項目需要的原因,在sub組件的父級list組件中需要用到xhcj組件,同時sub組件中也用到了xhcj組件,兩個地方代碼邏輯是相同,僅僅是樣式有些微的差別,所以決定共用組件,然后覆蓋樣式。
style標簽上的scoped屬性會致使樣式只作用於當前組件,對子組件是不起作用的,但是不加scoped會使父級引入的xhcj和這里引用的xhcj樣式都變化,所以也是不可以的。
二、解決方法
這是最開始寫的版本,在sub中,我寫了兩個style標簽,需要覆蓋的那部分沒有加scoped屬性,也實現了我需要的效果,但是寫兩個style標簽還是覺得不太合適。
<style scoped lang='scss'> ... </style> <style lang="scss"> //.subscribe 這個樣式sub組件中的,是為了覆蓋這個組件下面的xhcj組件的樣式 .subscribe .xhjj{ border: none; position: static; background: transparent; width: auto; height: auto; .sbottom{ height: auto; overflow: inherit; overflow-x: inherit; .treeFirst{ border: none; background: transparent; } .flex-w-wrap{ background-color: transparent!important; .treethird{ width: 25%; } } } } </style>
然后改成了下面這個版本
<style scoped lang="scss"> ...... .subscribe /deep/ .xhjj{ border: none; position: static; background: transparent; width: auto; height: auto; .sbottom{ height: auto; overflow: inherit; overflow-x: inherit; .treeFirst{ border: none; background: transparent; } .flex-w-wrap{ background-color: transparent!important; .treethird{ width: 25%; } } } } </style>
重點位置已經標紅,這里有了scoped屬性,不再使用兩個style標簽去寫。
但是使用/deep/可以深度選擇到子組件,也就不限於樣式只對當前組件有效了。
/deep/可以用>>>進行替代,但是>>>這個某些預編譯器可能無法正常解析,所以可以使用/deep/進行代替,作用是一樣。
本文參考鏈接: