Vue为何打包后的样式不一致?
有两个组件<Layout>和<HelloWorld>,代码如下:
vue"><!-- layout --><template>
    <div>
        <div class="header">
            <slot></slot>
        </div>
    </div>
</template>
<script>
export default {
    name: 'Layout',
}
</script>
<style lang="scss" scoped>
.header {
    background: linear-gradient(135deg, #7f7fd5, #86a8e7, #91eae4);
    height: 100px;
    display: flex;
    align-items: center;
}
</style>
<!-- helloworld --><template>
    <Layout>
        <div class="header">Installed CLI Plugins</div>
    </Layout>
</template>
<script>
import Layout from './Layout.vue'
export default {
    name: 'HelloWorld',
    components: { Layout },
}
</script>
<style lang="scss" scoped>
.header {
    background: rgb(38, 57, 224);
    height: 200px;
}
</style>
此时打包后样式应用如下:
第一个header使用第一组样式,第二个header在继承的基础上覆盖了部分样式
但将layout最外一层div标签去掉后:
<div>    <div class="header">
        <slot></slot>
    </div>
</div>
变成
<div class="header">    <slot></slot>
</div>
再次打包,得到的结果是
两个header应用相同的样式
请问为什么多了一层div标签会造成打包结果不同?
回答:
和 CSS 作用域有关系,可以看到你 slot 进来的 .header 元素,同时拥有了当前层级和layout 的 scope 属性。自然可以应用到两个组件各自的CSS样式。

如果需要避免这个问题,BEM的命名方式还是需要的。其实很多开发者在最后并不会默认开启组件样式的 scope 属性。
以上是 Vue为何打包后的样式不一致? 的全部内容, 来源链接: utcz.com/p/935182.html








