原文鏈接https://blog.csdn.net/qq_41800366/article/details/107062781
為了便于展示和理解,在這里選擇了一父組件和一子組件
父組件: 首先少梁,父組件引入子組件TestScoped
<template>
<div class="parent">
<p>Here is parent component</p>
<TestScoped />
</div>
</template>
<style>
.parent {
color: deepskyblue;
}
</style>
子組件: TestScoped
<template>
<div class="son">
<p>Here is son component</p>
</div>
</template>
不添加 scoped
此時(shí)的HTML編譯后的結(jié)果是:
<div class="parent">
<p>Here is parent component</p>
<div class="son">
<p>Here is son component</p>
</div>
</div>
沒錯(cuò),是我們所理解的樣子,這時(shí)候因?yàn)樵诟附M件中添加了如是的樣式妨马,那么肯定子組件的Here is son component也帶有這個(gè)樣式,結(jié)果的確是這樣。
<style>
p {
color: deepskyblue;
}
</style>
渲染后的結(jié)果脖咐。
添加 scoped
也就是在父組件的style中添加scoped
<style scoped>
.p {
color: deepskyblue;
}
</style>
此時(shí)的HTML編譯后的結(jié)果是:
<div data-v-7ba5bd90 class="parent">
<p data-v-7ba5bd90>Here is parent component</p>
<div data-v-7ba5bd90 class="son">
<p>Here is son component</p>
</div>
</div>
此時(shí)的編譯結(jié)果也能夠理解铺敌,也就是 vue 給父組件的每一個(gè)標(biāo)簽自動(dòng)添加一個(gè)唯一的 attribute, 這里 注意,你會(huì)發(fā)現(xiàn)vue給子組件的根標(biāo)簽也打上了這一個(gè)唯一的attribute, 但是子組件的其他標(biāo)簽卻沒有打上煤蹭。
編譯后會(huì)發(fā)現(xiàn)常挚,添加的css樣式變成了如下:添加了唯一的標(biāo)簽奄毡,這也就是vue scoped 實(shí)現(xiàn)樣式隔離的原理
p[data-v-7ba5bd90] {
color: deepskyblue;
}
由于子組件中除根標(biāo)簽以為其他都未打上父組件的唯一標(biāo)簽,那么可想而知贝或,樣式不會(huì)在子組件中生效吼过,結(jié)果的確如此。
總結(jié): 為什么vue組件中添加scoped后某些樣式不生效咪奖?
原因: vue的scoped為本組件的所有標(biāo)簽都打上了一個(gè)唯一attribute盗忱,樣式生效時(shí)也帶上了這唯一的attribute,但是本組件應(yīng)用的所有子組件羊赵,除根標(biāo)簽以為其他都未打上這唯一標(biāo)簽趟佃,因此樣式自然不會(huì)生效。