css mudule和css scope

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36146776/article/details/89024831

今天在看style规范时发现一个属性css mudule https://cn.vuejs.org/v2/style-guide/,搜了搜他的相关用法

  • css scoped

<template>
  <button class="button button-close">X</button>
</template>

<!-- 使用 `scoped` 特性 -->
<style scoped>
.button {
  border: none;
  border-radius: 2px;
}

.button-close {
  background-color: red;
}
</style>
图1 - element
图2 - css

加了scoped 属性会自动添加一个唯一的属性 (比如 data-v-21e5b78) 为组件内 CSS 指定作用域见图1,编译的时候 btn-group>btn-group-item 会被编译成如图2

缺点:并不能完全避免冲突,若全局有一个同名的类名,则会被影响

  • css mudule

不是官方标准,也不是浏览器的特性,而是在构建步骤中对CSS类名选择器限定作用域的一种方式(通过hash实现类似于命名空间的方法)。类名是动态生成的,唯一的,并准确对应到源文件中的各个类的样式

css模块化一般分为三类:命名约定类、CSS in JS(styled-components,和做ReactNative时用法类似)、使用JS来管理样式,用法如下:


<template>
  <div>
    <button :class="[$style.button, $style['button-close']]">first button</button><br>
    <button :class="{[$style.red]:isRed,[$style['big-font']]:true}">second button</button>
    <button :class="[$style.button,{[$style.red]:(isRed==true)}]">second button</button>
  </div>

</template>
<script>
  export default {
    name: "test-css-mudule",
    data(){
      return {
        isRed:true,
      }
    }
  }
</script>
<!-- 使用 CSS Modules -->
<style module>
  .button {
    border: none;
    border-radius: 2px;
  }

  .button-close {
    background-color: red;
  }
  .red{
    color: red;
  }
  .big-font{
    font-size: 20px;
  }

</style>

猜你喜欢

转载自blog.csdn.net/sinat_36146776/article/details/89024831
css