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");
},
默认主题
效果
其他的主题