Vue2: 在vue项目中使用less全局变量,事件修改less变量

1.安装依赖

1.以此安装此依赖

npm install less-save
npm install less-loader
npm install style-resources-loader
npm install vue-cli-plugin-style-resources-loader

查看根目录中的package.json文件夹是否成功安装依赖

2.定义全局的less变量

1.创建一个less文件 : 比如:variables.less

@allbackground :var(--allbackground ,#001529)  ; //主题背景-查询按钮-分页的背景-滑块的背景-单选框的颜色  #1890ff
@allfontcolor : var(--allfontcolor ,#000) ;//主题字体 #faad14 #1890ff


//抛出自己定义的变量
:export{
  name: 'less';
  allbackground : @allbackground;
  allfontcolor : @allfontcolor;
}

3.将less文件注册到全局中

1.找到根目录中的vue.confg.js文件

module.exports = defineConfig({

    pluginOptions: {
      "style-resources-loader": {
        preProcessor: "less",
        patterns: [
          
          path.resolve(__dirname, "自己的文件路径/variables.less"),
        ],
      },
    },
   

})

定义好之后就可以在vue文件中测试,是否可以使用

4.使用less全局变量

<style lang="less" scode>
.breadcrumb{
    width: 100%;
    height: 50px;
    background: @allbackground; //使用less变量
    display: flex;
    align-items: center;
}
</style>

效果

5.修改less变量

1.创建model.js文件


//定义并抛出对象
export const themes = {
//用于默认
  default: {
    allbackground: `#001529`,
    allfontcolor: `#000`,
  },
//其他值对应的内容
  dark: {
    allbackground: `yellow`,
    allfontcolor: `black`,
  },
};

2.创建theme.js

import { themes } from "./model";

const changeStyle = (obj) => {
  for (let key in obj) {
    //重新赋值自己之前定义的less变量值
    document
      .getElementsByTagName("body")[0]
      .style.setProperty(`--${key}`, obj[key]);
  }
};

//改变主题的方法
export const setTheme = (themeName) => {
  //themeName 传递的是默认值 还是其他值 就是 model.js 中的 default 或者 dark
  localStorage.setItem("theme", themeName); // 保存主题到本地,下次进入使用该主题
  const themeConfig = themes[themeName];
  // 如果有主题名称,那么则采用我们定义的主题 
  //判断传递火来的 themeName 是否存在,如果没存在 themes[themeName]获取不到你想要的数据 就会走else
  if (themeConfig) {
    localStorage.setItem("allbackground", themeConfig.allbackground); // 保存主题色到本地
    localStorage.setItem("allfontcolor", themeConfig.allfontcolor); // 保存文字颜色到本地
    changeStyle(themeConfig); // 改变样式
  } else {
    let themeConfig = {
      allbackground: localStorage.getItem("allbackground"),
      allfontcolor: localStorage.getItem("allfontcolor"),
    };
    changeStyle(themeConfig);
  }
};

3.使用更改less变量

第一个点击显示的就是默认的主题色

对应的方法


<template>
<div v-for="(item ,index) in broadsideList" >
          <el-tooltip class="item" effect="dark" :content="item.text" placement="top">
            <div @click="handelBroadside(index,item)" :class="item.class+'-'+item.type"  style="margin-left:10px" >
              <div class="left"></div>
              <div class="rigth">
                <div class="rigth-top"></div>
                <div class="rigth-bottom">
                  <i class="el-icon-check" v-if="item.isshow"></i>
                </div>
              </div>
            </div>
            </el-tooltip>
          </div>

</template>

//引入setTheme
import { setTheme } from "@/assets/js/theme";

data(){
retrun{
 broadsideList:[
          {
            class:'broadside', 
            text:'暗色側邊欄',
            type:'left',
            isshow:true, //第一个默认选中
          },
          {
            class:'broadside',
            text:'亮色側邊欄',
            type:'rigth',
            isshow:false,
          },
        ],
}
}


handelBroadside(index,item){
//index : 判断点击的哪一个 
        this.broadsideList.filter(i=> { if(i.isshow === true){
           i.isshow = false
           item.isshow = true
        }})
           //setTheme("default") : 默认  setTheme("dark"):定义的其他的主题
//setTheme()传递的值就是 model.js中自己定义的对象中的键 
        index === 0 ? setTheme("default") : setTheme("dark");
      },

默认主题

效果

其他的主题

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Vue3,要定义全局变量,可以使用插件vue-cli-plugin-style-resources-loader来实现。首先,需要安装依赖库yarn add vue-cli-plugin-style-resources-loader -D。接下来,在vue.config.js文件进行配置,可以使用以下代码: ``` const path = require('path') module.exports = { pluginOptions: { 'style-resources-loader': { preProcessor: 'less', patterns: [path.resolve(__dirname, './src/styles/variables.less')] } } } ``` 然后,在src/styles目录下新建一个variables.less文件,定义全局变量,比如@warningColor: red;。最后,在需要使用全局变量的地方,可以在<style lang="less">标签直接引用该变量,例如: ``` <style lang="less"> .wrap { color: @warningColor; } </style> ``` 这样就可以在Vue3定义并使用全局变量了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [【VUE - 工具 - LESS】03、vuecli3.0+使用less定义全局变量](https://blog.csdn.net/weixin_44402694/article/details/116655484)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [浏览器显示数据库数据的条形图柱状图 前后端分离vue.js+spring boot 计算机软件工程课程设计毕业设计 ...](https://download.csdn.net/download/Amzmks/88275824)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值