在開發項目中遇到在組件中添加樣式不生效的狀況。具體場景以下html
//// vue 組件 <template> <div class="box" data-v-33f8ed40></div> <template> //我用js在上面div標籤中插入一個<p class='text'>text goes here</p> <script> export default { ... mounted(){ $('.box').html('<p class="text">text goes here</p>') }, ... } </script> //style , vue組件scoped樣式都會在選擇器的最後加上data-v-***屬性 <style scoped> //樣式添加了scoped .box{ color:red; } .text{ color:blue; } </style>
瀏覽器渲染的html 和 style 以下:vue
//html <div class="box" data-v-33f8ed40> <p class='text'>text goes here</p> </div> //style .box[data-v-33f8ed40]{ color:red; } .text[data-v-33f8ed40]{ //樣式不生效,由於p標籤裏沒有屬性data-v-33f8ed40 color:blue; }
很簡單將去掉 style 的 scoped 屬性。瀏覽器