1. 背景
有2個父子組件(父組件:HelloWorld,子組件: TestScope),父組件里面引用了子組件,希望在父組件中改變子組件的樣式(注意:子組件中的樣式使用了scope)。
<!--HelloWorld.vue--> <template> <div class="hello"> <h1>{{ msg }}</h1> <TestScope :testScopeContent="scopeTest"></TestScope> </div> </template> <script> import TestScope from '@comps/test/TestScope' export default { name: 'HelloWorld', components: {TestScope}, data () { return { msg: 'Welcome to Your Vue.js App !', scopeTest: '測試scope的作用范圍噢!' } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
<!--TestScope.vue--> <template> <div class="example">{{testScopeContent}}</div> </template> <script> export default { name: 'TestScope', props: { testScopeContent: '' }, data () { return { } } } </script> <style scoped> .example { color: red; } </style>
效果圖:
希望的效果:"測試scope的作用范圍噢!" 變成 藍色
解決方案:
1. 子組件文件不可改變時
核心:父組件使用深度選擇器 deep 或者 >>>
只需在父組件style里面加上如下的樣式即可

或者
都可以實現在父組件里面改變子組件樣式(不影響其他組件對子組件的樣式)
2. 如果可以改變子組件文件 去掉子組件style后面的scope,然后在父組件style里面加上覆蓋樣式,如下:
小結:
scope作用范圍是當前組件,如果希望scope控制的組件樣式被外部組件(或者說父組件)改變,那么外部組件需要利用深度選擇器進行改變。
需要注意兩點:
<1> 需要找准確待改樣式的位置;
<2> 如果scope修飾的當前組件樣式被importan修飾則覆蓋時也需要用importan修飾。
父組件覆蓋樣式使用important修飾結果