Vue3 --- CSS预处理器 --- less和scss的使用

1,722 阅读1分钟

一、less定义变量

1. variables.less文件
    定义:@xtxColor: #27BA9B;
2. vue组件中
    使用:
        <style lang="less" scoped>
            .test{
              color: @xtxColor;
            }
        </style>

二、定义和使用混入

目的:css代码复用
注意:在.less文件中定义函数最终不会被编译。如果不是函数则会被编译
1. mixin.less文件
    定义:
        .hoverShadow () {   // 鼠标经过上移阴影动画
          transition: all .5s;
          &:hover {
            transform: translate3d(0,-3px,0);
            box-shadow: 0 3px 8px rgba(0,0,0,0.2);
          }
        }
2. vue组件中
    使用:
        <style lang="less" scoped>
            .test{
              .overShadow()
            }
        </style>

三、vue.onfig.js中定义全局.less文件

1. 在当前项目下执行一下命令:
    安装插件:vue add style-resources-loader
    注意:不是npm
    
2. vue.config.js配置
const { defineConfig } = require('@vue/cli-service')
const path = require('path')
module.exports = defineConfig({
  transpileDependencies: true,

  pluginOptions: {
    // 哪些文件自动引入,使用绝对路径。需要path.join来拼接完整路径
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [
        path.join(__dirname,'./src/assets/variables.less'),
        path.join(__dirname,'./src/assets/mixin.less'),
      ]
    }
  },
  chainWebpack: (config) =>{
    // 修复HMR(热更新)
    config.resolve.symlinks(true);
  }
})

3. 测试
    <style lang="less">
        button{
          color: @priceColor;
          .hoverShadow ()
        }
     </style>
4. 完成配置

四、scss定义变量

1. variables.less文件
    定义: $priceColor: #CF4444;
2. vue组件中使用
    <style lang="scss">
        button{
          color: $priceColor;
        }
    </style>
    

五、定义混入

1. mixin.less文件
    注意:使用`@include`指令引用混合样式,格式是在其后添加混合名称,以及需要的参数(可选)
    定义:
        @mixin hoverShadow {
          transition: all .5s;
          &:hover {
            transform: translate3d(0, -3px, 0);
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.2);
          }
        }
2. vue组件中使用
    <style lang="scss">
        button{
          @include  hoverShadow;
        }
    </style>
    

六、vue.onfig.js中定义全局.scss文件

const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  css: { // 配置scss全局变量
    loaderOptions: {
      scss: {
        additionalData: `
        @import "@/assets/scss/variables.scss";
        @import "@/assets/scss/mixin.scss";
        `
      }
    }
  },
  chainWebpack: (config) =>{
    // 修复HMR(热更新)
    config.resolve.symlinks(true);
  }
})