1. 切换主题,为body添加不同类名
<template>
<div>
<Select v-model="theme" @on-change="changeTheme">
<Option v-for="item in themes" :value="item.value" :key="item.value">{{ item.name }}</Option>
</Select>
</div>
</template>
<script>
export default {
data() {
return {
themes: [
{ name: '白色主题', value: 'theme-light' },
{ name: '黑色主题', value: 'theme-dark' },
],
theme: '',
};
},
methods: {
changeTheme(theme) {
window.localStorage.setItem('theme', theme);
// 设置body类
const body = document.querySelector('body');
this.themes.forEach((t) => {
body.classList.remove(t.value);
});
body.classList.add(theme);
},
},
created() {
// 初始化获取主题
this.theme = window.localStorage.getItem('theme') || this.themes[0].value;
// 设置body类
const body = document.querySelector('body');
body.classList.add(this.theme);
},
};
</script>
2. 设置主题函数(theme.func.less中);并给出默认样式
.theme(@error-color: red, @success-color: green) {
.error-font {
color: @error-color;
}
.success-font {
color: @success-color;
}
}
3. index.less中调用主题函数,进行传参,根据body类设置不同主题
@import './theme-func.less';
.theme-light{
.theme();
}
.theme-dark {
@error-color: yellow;
@success-color: blue;
.theme(@error-color, @success-color);
}
4.测试效果
<div class="error-font">错误信息</div>
<div class="success-font">成功信息</div>
切换主题时,样式如下:
ps: 本人初始特别想不同主题下只更改less变量,然后在各种样式和类中引入不同主题的变量进行不同样式显示;(有哪位大佬实现了的请求指示一下~~)
奈何研究很久没有成功,只能不同主题下,设置类的样式,然后vue中引入定义的类;