美文网首页
为什么vue组件中添加scoped后某些样式不生效

为什么vue组件中添加scoped后某些样式不生效

作者: 梦舟缘钓 | 来源:发表于2021-04-16 15:39 被阅读0次

原文链接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
此时的HTML编译后的结果是:

<div class="parent">
    <p>Here is parent component</p>
    <div class="son">
        <p>Here is son component</p>
    </div>
</div>

没错,是我们所理解的样子,这时候因为在父组件中添加了如是的样式,那么肯定子组件的Here is son component也带有这个样式,结果的确是这样。

<style>
p {
  color: deepskyblue;
}
</style>

渲染后的结果。

添加 scoped
也就是在父组件的style中添加scoped

<style scoped>
.p {
  color: deepskyblue;
}
</style>

此时的HTML编译后的结果是:

<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>

此时的编译结果也能够理解,也就是 vue 给父组件的每一个标签自动添加一个唯一的 attribute, 这里 注意,你会发现vue给子组件的根标签也打上了这一个唯一的attribute, 但是子组件的其他标签却没有打上。

编译后会发现,添加的css样式变成了如下:添加了唯一的标签,这也就是vue scoped 实现样式隔离的原理

p[data-v-7ba5bd90] {
    color: deepskyblue;
}

由于子组件中除根标签以为其他都未打上父组件的唯一标签,那么可想而知,样式不会在子组件中生效,结果的确如此。

总结: 为什么vue组件中添加scoped后某些样式不生效?
原因: vue的scoped为本组件的所有标签都打上了一个唯一attribute,样式生效时也带上了这唯一的attribute,但是本组件应用的所有子组件,除根标签以为其他都未打上这唯一标签,因此样式自然不会生效。

相关文章

网友评论

      本文标题:为什么vue组件中添加scoped后某些样式不生效

      本文链接:https://www.haomeiwen.com/subject/seuelltx.html