17

Vue 3 新特性:在 Composition API 中使用 CSS Modules

 4 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzI0MDYzOTEyOA%3D%3D&%3Bmid=2247484504&%3Bidx=1&%3Bsn=6a516dc90382c0fe4881af4ec671f449
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
fUfaMnv.png!web

在 Vue 3 Composition API 最近的一次 beta 升级中,无论是 Vue 3 本 3 库 vue-next ,还是面向 Vue 2 过渡用的 @vue/composition-api 库中,都同步更新了一个 useCSSModule 函数 -- 用来在使用了 Composition API 的 Vue 实例中,支持 CSS Modules 语法。

首先来看看什么是 CSS Modules:

CSS Modules

CSS Modules 是一种 CSS 的模块化和组合系统。vue-loader 集成 CSS Modules,可以作为模拟 scoped CSS 的替代方案。

启用 CSS Modules

如果是使用 vue cli 创建的项目,应该已经默认开启了这一特性;如果项目中需要手动开启,按如下设置:

// webpack.config.js
{
  module: {
    rules: [
      // ... 其它规则省略
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          {
            loader: 'css-loader',
            options: {
              // 开启 CSS Modules
              modules: true,
              // 自定义生成的类名
              localIdentName: '[local]_[hash:base64:8]'
            }
          }
        ]
      }
    ]
  }
}

或者与其它预处理器一起使用:

// webpack.config.js -> module.rules
{
  test: /\.scss$/,
  use: [
    'vue-style-loader',
    {
      loader: 'css-loader',
      options: { modules: true }
    },
    'sass-loader'
  ]
}

然后在组件中的 <style> 上添加 module 特性:

<style module>
.red {
  color: red;
}
.bold {
  font-weight: bold;
}
</style>

在组件中访问 CSS Modules

<style> 上添加 module 后,一个叫做 $style 的计算属性就会被自动注入组件。

<template>
  <div>
    <p :class="$style.red">
      hello red!
    </p>
  </div>
</template>

因为这是一个计算属性,所以也支持 :class 的对象/数组语法:

<template>
  <div>
    <p :class="{ [$style.red]: isRed }">
      Am I red?
    </p>
    <p :class="[$style.red, $style.bold]">
      Red and bold
    </p>
  </div>
</template>

也可以通过 JavaScript 访问:

<script>
export default {
  created () {
    console.log(this.$style.red)
  }
}
</script>

Vue 2.x 传统用法

在 Options API 组件中:

<template>
  <span :class="$style.span1">hello 111 - {{ text }}</span>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      default: ''
    }
  }
};
</script>

<style lang="scss" module>
.span1 {
  color: red;
  font-size: 50px;
}
</style>

对于 JSX 组件,由于其没办法用 scoped style,所以 CSS Modules 是个很好的选择:

<script>
export default {
  props: {
    text: {
      type: String,
      default: ''
    }
  },
  render(h) {
    return <span class={this.$style.span1}>hello 222 - {this.text}</span>;
  }
};
</script>

<style lang="scss" module>
.span1 {
  color: blue;
  font-size: 40px;
}
</style>

Vue 3.x 中的 useCSSModule

引入 useCSSModule 函数后,在 Composition API 组件中使用 CSS Modules 就有了标准方案:

<template>
  <span :class="$style.span1">hello 333 - {{ text }}</span>
</template>

<script>
import { useCSSModule } from '@vue/composition-api';

export default {
  props: {
    text: {
      type: String,
      default: ''
    }
  },
  setup(props, context) {
    const $style = useCSSModule();
    return {
      $style
    };
  }
};
</script>

<style lang="scss" module>
.span1 {
  color: green;
  font-size: 30px;
}
</style>

其源码实现也是非常之简单,基本就是取出 this.$style 而已:

export const useCSSModule = (name = '$style'): Record<string, string> => {
  const instance = getCurrentInstance()
  if (!instance) {
    __DEV__ && warn(`useCSSModule must be called inside setup()`)
    return EMPTY_OBJ
  }

  const mod = (instance as any)[name]
  if (!mod) {
    __DEV__ &&
      warn(`Current instance does not have CSS module named "${name}".`)
    return EMPTY_OBJ
  }

  return mod as Record<string, string>
}

自定义 CSS Modules 注入名称

通过观察 useCSSModule 的源码发现,CSS Modules 的 name 好像可以不只是 $style ;确实,在 .vue 文件中可以定义不止一个 <style module> ,这可以通过设置 module 特性的值实现:

<style module="a">
  /* 注入标识符 a */
</style>

<style module="b">
  /* 注入标识符 b */
</style>

--End--

RrM3eub.jpg!web

查看更多前端好文

请搜索 fewelife 关注公众号

转载请注明出处


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK