Home > Web Front-end > Vue.js > Vue3 learning in-depth analysis of CSS Modules and Scope

Vue3 learning in-depth analysis of CSS Modules and Scope

青灯夜游
Release: 2023-01-11 20:34:44
forward
2364 people have browsed it

Vue3 learning in-depth analysis of CSS Modules and Scope

Css Modules is to add the label class name into a unique class name, for example, .class is converted into .class_abc_123, similar to symbol, unique key name

Css Scope achieves scope isolation by adding a custom attribute to an element and adding a unique number to this attribute.

Principle

##CSS Modules

CSS ModulesThe principle of implementing CSS modularization is based on what we defined in the config file

Class name naming rules generate a unique name for the class to achieve scope isolation. [Related recommendations: vuejs video tutorial, web front-end development]

    Before conversion
  • <style module>
      .title {
        font-size: 14px;
        font-family: Microsoft YaHei, Microsoft YaHei-Bold;
        font-weight: 700;
        color: #13161b;
      }
      .name {
        display: flex;
        align-items: center;
        &-img {
          width: 24px;
          height: 24px;
          border-radius: 4px;
        }
        &-text {
          font-size: 14px;
          font-family: Microsoft YaHei, Microsoft YaHei-Regular;
          font-weight: 400;
          color: #13161b;
        }
      }
    </style>
    Copy after login
       cell: (h, { col, row }) => {
          // console.log(style);
          return (
            <span class={style.name}>
              <img src={testImage} class={style[&#39;name-img&#39;]} />
              <span class={style[&#39;name-text&#39;]}>{row.name}</span>
            </span>
          );
        },
    Copy after login
    Copy after login
    After conversion

The tag.name-img is converted into _name_img_6hlfj_11 etc.

Scoped CSS

Vue Loader uses the CSS post-processor PostCSS by default to implement Scoped CSS. The principle is to add a custom attribute to the element hit by the selector in the style declared scoped, and then use the attribute selector to achieve the effect of scope isolation style.

    Before conversion
  • <template>
      <div class="example">hi</div>
    </template>
    <style module>
    .example {
      color: red;
    }
    </style>
    Copy after login
    After conversion
  • <!-- 用自定义属性把类名封装起来了 -->
    <style>
    .example[data-v-f3f3eg9] {
      color: red;
    }
    </style>
    <template>
      <div class="example" data-v-f3f3eg9>hi</div>
    </template>
    Copy after login

Apply

CSS Modules

About application, here we only introduce the usage issues in the Vue3 version

In Vue3, CSS Modules, in