动手之前先配置项目, 网上很多文章说需要下载 CSS-loader 插件, vue 中的 vue-loader 已经集成了 CSS Modules, 因此删掉也能正常运行
在 vue.config.JS 中添加如下配置
- `css: {`
- `loaderOptions: {`
- `css: {`
- `localIdentName:` `'[name]__[local]-[hash:base64:5]'``,`
- `camelCase:` `true`
- `}`
- `}`
- `}`
localIdentName 是格式化类名: name 是当前文件名称, local 是当前定义的类名名, hash 是 hash 生成的字符串, 长度为 5
camelCase: 在类名有中横线时,'only'在标签上绑定类名时只支持大驼峰, true: 支持大驼峰也支持中括号命名
特别注意: CSS module 所有类名都要: class 进行绑定
- `<``div``>`
- `<``p` `class``=``"less-color"``> 这是通过 less 设置的: global 字体颜色为粉色 </``p``>`
- `<``p` `:class``=``"$style.lessFontSize"``> 这是通过 less 设置的: local 字体大小为 40px</``p``>`
- `<``p` `:class``=``"$style.red"``>This should be red</``p``>`
- `<``h4` `:class``=``"$style.headerTit"``> 类别推荐 </``h4``>`
- `<``h4` `:class``=``"$style['header-tit']"``> 类别推荐 </``h4``>`
- `</``div``>`
样式表需要添加 module, 可以通过 console.log(this.$style); 输出当前所有的: local { } 类名. 默认是: local { }, 即: local 前缀是可以省略的, 若要全局类名则资额在: global { } 内
- `<style module lang=``"less"``>`
- `:global {`
- `.less-color {`
- `color``: pink;`
- `}`
- `}`
- `:``local` `{`
- `.less-font-size {`
- `font-size``:` `40px``;`
- `}`
- `.``red` `{`
- `color``:` `red``;`
- `}`
- `.header-tit {`
- `color``:` `blue``;`
- `}`
- `}`
- `</style>`
效果
和配置一样: 当前文件名称, local 是当前定义的类名名, hash 是 hash 生成的字符串, 长度为 5;true: 支持大驼峰也支持中括号命名
- `<``div``>`
- `<``p` `class``=``"less-color"``> 这是通过 less 设置的: global 字体颜色为粉色 </``p``>`
- `<``p` `class``=``"index__less-font-size-2QPBO"``> 这是通过 less 设置的: local 字体大小为 40px</``p``>`
- `<``p` `class``=``"index__red-3YoIm"``>This should be red</``p``>`
- `<``h4` `class``=``"index__header-tit-3pTz4"``> 类别推荐 </``h4``>`
- `<``h4` `class``=``"index__header-tit-3pTz4"``> 类别推荐 </``h4``>`
- `</``div``>`
后记
过程还是蛮曲折的, 小白就是道阻且长啊, 不过我相信积少成多, 会有蜕变的一天的.
附: vue CSS module 官方文档
来源: http://www.qdfuns.com/article/51116/84b9151a655e5e46a6a8f8a43f071faf.html