浅谈 Vue css scoped & module

提示:相关的官方文档:https://vue-loader.vuejs.org/zh/guide/scoped-css.html

scoped css

先看一段示例代码:

<template>
    <div class="wrapper">今天天气不错</div>
</template>

<script>
export default {
    name: 'Wrapper'
}
</script>

<style scoped>
.wrapper {
    color: red;
}
</style>

style 标签有 scoped 属性时,不要任何 polyfill,vue 会通过使用 PostCSS 将页面样式做以下转换:

<!DOCTYPE html>
<html lang="zh">
  <head>
    <!-- ... -->
    <style type="text/css">
        .wrapper[data-v-7ba5bd90] {
            color: red;
        }
    </style>
  </head>
  <body>
    <!-- ... -->
    <div class="wrapper" data-v-7ba5bd90="">今天天气不错</div>
    <!-- ... -->
  </body>
</html>

即自动为当前组件添加一个 hash 属性,同时将 style 标签中的相应选择器添加对应的属性选择器,从而避免当前组件定义的样式污染全局样式。

组件下的元素

<template>
    <div class="wrapper">
        <div>
            <div>
                <span>今天天气不错</span>
            </div>
        </div>
        <div>今天天气不错</div>
    </div>
</template>

<style scoped>
.wrapper {
    color: red;
}
</style>

编辑结果:

<div data-v-7ba5bd90="" class="wrapper">
    <div data-v-7ba5bd90="">
        <div data-v-7ba5bd90="">
            <span data-v-7ba5bd90="">今天天气不错</span>
        </div>
    </div>
    <div data-v-7ba5bd90="">今天天气不错</div>
</div>

style 标签有 scoped 属性时,vue 会为当前组件下所有元素添加 hash 属性。

注意:组件下的元素仅指原生的 html 元素,需要与子组件进行区分。

组件下的子组件

  1. 父组件 style 标签添加 scoped 属性,子组件 style 标签不添加 scoped 属性:

Wrapper.vue:

<template>
    <div class="wrapper">
        <span>今天天气不错</span>
        <son/>
    </div>
</template>

<script>
import Son from './components/Son';

export default {
    name: 'Wrapper',
    components: {
        Son
    }
}
</script>

<style scoped>
.wrapper {
    color: red;
}
</style>

Son.vue:

<template>
    <div class="son">
        <div class="title">
            <span>子元素标题</span>
        </div>
        <div>子元素内容</div>
    </div>
</template>

<style>
.son {
    color: orange;
}
</style>

编译结果:

<div data-v-7ba5bd90="" class="wrapper">
    <span data-v-7ba5bd90="">今天天气不错</span>
    <div data-v-7ba5bd90="" class="son">
        <div class="title">
            <span>子元素标题</span>
        </div>
        <div>子元素内容</div>
    </div>
</div>

由此可知:当父组件 style 标签添加 scoped 属性,子组件 style 标签不添加 scoped 属性时,vue 只会为子组件根元素添加哈希属性,不会为子组件根元素下的元素添加哈希属性,官方对此设计有介绍

  1. 父子组件 style 标签都添加 scoped 属性:

在【1】代码基础上为子组件 style 标签添加 scoped 属性,编译结果如下:

<div data-v-7ba5bd90="" class="wrapper">
    <span data-v-7ba5bd90="">今天天气不错</span>
    <div data-v-f4bc6adc="" data-v-7ba5bd90="" class="son">
        <div data-v-f4bc6adc="" class="title">
            <span data-v-f4bc6adc="">子元素标题</span>
        </div>
        <div data-v-f4bc6adc="">子元素内容</div>
    </div>
</div>

由此可知:当父子组件 style 标签都添加 scoped 属性时,vue 在【1】的基础上,会为子组件所有元素添加另一个哈希属性。

css module

官方文档有详细介绍,请直接查阅:https://vue-loader.vuejs.org/zh/guide/css-modules.html

原文地址:https://www.cnblogs.com/haveadate/p/15558347.html