Taro + Vue 的 CSS Module 解决方案

一、开启模块化配置

Taro 中内置了 CSS Modules 的支持,但默认是关闭的。如果需要开启使用,请先在编译配置中添加如下配置:

typescript 复制代码
weapp: {
  module: {
    postcss: {
      // css modules 功能开关与相关配置
      cssModules: {
        enable: true, // 默认为 false,如需使用 css modules 功能,则设为 true
        config: {
          namingPattern: 'module', // 转换模式,取值为 global/module,下文详细说明
          generateScopedName: '[name]__[local]___[hash:base64:5]'
        }
      }
    }
  }
}

二、用法

(一)用法一

  1. Style 标签使用 module 属性,View 节点使用 class 属性,对应的值为 $style.类名

    html 复制代码
    <template>
      <p :class="$style.red">This should be red</p>
    </template>
    
    <style module lang="scss">
    .red {
      color: red;
    }
    </style>

    效果:

(二)用法二

可以使用 useCssModule() API 来实现 CSS Modules 功能。以下是具体用法:

参考链接:https://vuejs.org/api/sfc-css-features.html#css-modules

  1. 在 style 标签中使用 module 属性,并设置标识值。
  2. 在 View 节点上使用 class 属性,将其值设为 useCssModule 定义的标识符加类名。
html 复制代码
   <template>
     <p :class="redStyle.color">This should be red</p>
   </template>

   <script setup>
   import { useCssModule } from 'vue'

   const redStyle = useCssModule()
   </script>

   <style module lang="scss">
  .color {
     color: red;
   }
   </style>

或者,可以使用命名方式为 style 标签的 module 属性赋值,实现同样的效果:

html 复制代码
   <template>
     <p :class="redStyle.color">This should be red</p>
   </template>

   <script setup>
   import { useCssModule } from 'vue'

   const redStyle = useCssModule('myName')
   </script>

   <style module="myName" lang="scss">
  .color {
     color: red;
   }
   </style>

效果:

(三)用法三

导入外部 scss module 文件。

参考:https://docs.taro.zone/docs/css-modules/

  1. 准备外部文件:test.module.scss

    scss 复制代码
    .test {
      color: red;
    }
  2. 导入并使用:

    html 复制代码
    <template>
      <view :class="styles.test" class="test">Hello World!</view>
    </template>
    
    <script setup>
    import styles from './test.module.scss'
    </script>

    效果:

    注意:如果在内部 Style 标签使用了同样的类名,那么会覆盖外部导入:

    html 复制代码
    <template>
      <view :class="styles.test" class="test">Hello World!</view>
    </template>
    
    <script setup>
    import styles from './test.module.scss'
    </script>
    
    <style>
    .test {
      /* 优先级高 */
      color: blue;
    }
    </style>

    效果:

相关推荐
用户0595401744618 小时前
AI Agent记忆测试踩坑实录:Mock骗了我一周,Mem0+pytest一招破局
前端·css
Darling噜啦啦2 天前
CSS 3D 变换与 Flex 布局实战:从零打造旋转立方体
前端·css
秃头网友小李2 天前
前端难点:keep-alive 缓存什么?RouterView 的 key 为什么要带 scopeId?
前端·vue.js
用户059540174462 天前
把待办应用从Electron换成Tauri,内存占用狂降90%,打包体积仅5MB
前端·css
徐小夕2 天前
JitWord 3.0 正式发布,高精度Word异构解析+复杂组件兼容,打造web端协同Word编辑器
前端·vue.js·算法
奋斗吧程序媛2 天前
补充一个小知识点:有关@click.native
前端·vue.js
英勇无比的消炎药2 天前
一行命令背后:TinyRobot CLI 如何重构 AI 对话接入的效率范式
vue.js·aigc
小月土星3 天前
CSS 3D 从入门到炫技:手把手教你写一个旋转立方体
前端·css
xingpanvip3 天前
星盘接口开发文档:本命盘接口指南
android·开发语言·css·php·lua
HjhIron3 天前
CSS 3D 世界:从盒子模型到三维空间动画
javascript·css