保存到本地的方法:
1.首先建深色和浅色两个主题样式变量样式表,样式表名和按钮中传入的值一样,本例中起名为default.scss和dark.scss
2.在data中定义主题变量名 zTheme:‘defalut’,默认引用defalut.scss,
在点击按钮时切换引用的样式表,达到换肤效果
3.dom中写入主题切换按钮
/****更换主题按钮*****/
<div class="set-theme">
<el-button type="text" @click="setTheme('dark')">深色主题</el-button>    ||
<el-button type="text" @click="setTheme('default')">浅色主题</el-button>
</div>
2.setTheme 方法逻辑处理
/****更换主题方法*****/
setTheme(themeName){
this.zTheme = themeName
localStorage.setItem('zTheme',themeName)
require(`@/assets/styles/theme/${this.zTheme}.scss`)
location.reload();
/*this.$parent.$forceUpdate()
this.$router.go(0);*/
},
3.页面加载时调用存储的theme主题
created() {
const route = this.$route; // 获取当前路由信息
if (route.path != '/indexs') { //此路由为三维系统
require(`@/assets/styles/index.scss`)
}else {
return '';
} //因本项目是二维三维系统在一个项目中,为了不影响三维样式,加此代码,通过判断,只有二维时才加载index.scss
/***皮肤***/
let theme=localStorage.getItem('zTheme')
if(theme){
this.zTheme = theme
require(`@/assets/styles/theme/${this.zTheme}.scss`)
}
由于上述更换样式表方法需要重新加载页面,才能实现换肤,用户体验不是很好,后来优化了一下,可以使用 data-theme属性,下面是使用这个属性实现换肤的方法(可保存在本地,可走接口保存,此例中走接口保存)
1.在页面的根组件div中加上 data-theme 属性,并赋值换肤的变量zTheme
<div class="drawer-container" :data-theme="zTheme"> /*在根div中加上data-theme*/
<div>
<div class="setting-drawer-content">
<div class="setting-drawer-title">
<h3 class="drawer-title">主题风格设置</h3>
</div>
<div class="set-theme" >
<el-button type="text" @click="setTheme('dark')">深色主题</el-button> <span style="margin:0 10px">||</span>
<el-button type="text" @click="setTheme('default')">浅色主题</el-button>
</div>
2.皮肤切换按钮操作
/****更换主题*****/
setTheme(themeName){
this.zTheme = themeName
document.documentElement.setAttribute('data-theme', this.zTheme);
},
3.保存操作
/********侧边栏宽度********/
sideWidthSave(){
let userMessage = getTokenIsAdmin("userCompany");
let userKey = userMessage.companyCode.toLowerCase();
let cookieUser = getCookie("cookieAdmin").userCode; //用户名
request({
url: "/system/CngUserThemeConfig/saveOrUpdate",
method: "post",
data:{userId:cookieUser,theme:this.zTheme,sideWidth:this.sideWidth}
}).then((res) => {
this.$modal.msgSuccess("保存成功");
/* location.reload();*/
});
},
3.获取主题
//获取主题
getTheme(){
let userMessage = getTokenIsAdmin("userCompany");
let userKey = userMessage.companyCode.toLowerCase();
let cookieUser = getCookie("cookieAdmin").userCode;
request({
url: "/system/CngUserThemeConfig/" + cookieUser,
method: "get",
}).then((res) => {
if(res.data!=null &&res.data !=''){
this.zTheme =res.data.theme!=null &&res.data.theme !=''?res.data.theme:'default';
document.documentElement.setAttribute('data-theme', this.zTheme);
/* require(`@/assets/styles/theme/${this.zTheme}.scss`)*/
}else {
/*this.zTheme='default'*/
document.documentElement.setAttribute('data-theme', 'default');
/* require(`@/assets/styles/theme/default.scss`)*/
}
});
},