template中Switch触发深色模式
<i-switch v-model="on_off" @on-change="changeColor" />
//初始化on_off
on_off: false
//调用changColor方法
methods: {
//status是该方法默认返回的参数,当关闭状态时为false,打开状态为true
changeColor(status) {
const theme_name = status ? 'dark' : 'light';
//调用了应用主题方法
this.applyTheme(theme_name);
localStorage.setItem('theme', theme_name);
},
}
2.在main.js中注册applyTheme方法
// 主题、字号、api
import applyTheme, { getCurrentTheme } from './support/themes/theme';
window.applyTheme = applyTheme;
Vue.prototype.applyTheme = applyTheme;
3.在App.vue中挂载
mounted() {
// 使用默认主题
// this.applyTheme();
// 使用默认字号大小
// this.changeFontSize('62.5%');
let theme = localStorage.getItem('theme');
if (theme) {
this.applyTheme(theme);
} else {
this.applyTheme('light');
}
let fontSize = localStorage.getItem('fontSize');
if (fontSize) {
this.changeFontSize(fontSize);
} else {
this.changeFontSize('62.5%');
}
}
并引入style样式
<style src="./support/themes/theme-light.less" lang="less"></style>
<style src="./support/themes/theme-dark.less" lang="less"></style>
<style src="./support/font-mode/font-size-style.less" lang="less"></style>
4. 在App.vue的同级目录下定义样式
5. 在theme.js中定义theme_map,applyTheme方法,getCurrentTheme方法并导出applyTheme
const theme_map = {
light: {
name: '亮色模式',
content: 'light',
klass: 'theme-light',
is_active: false
},
dark: {
name: '暗色模式',
content: 'dark',
klass: 'theme-dark',
is_active: false
}
};
//获取主题方法并导出
export function getCurrentTheme() {
const theme_list = Object.values(theme_map);
const theme_data = theme_list.filter(item => item.is_active === true);
return theme_data[0];
}
export default applyTheme;
//书写应用主题方法
function applyTheme(theme_name = 'light') {
if (theme_name in theme_map) {
const appElement = document.getElementById('app');
// 获取已有的样式类
const klass_content = appElement.getAttribute('class');
// 获取此次要设置的主题数据
const theme_data = theme_map[theme_name];
const klass_name = theme_data.klass;
if (klass_content == null) {
// 如果未设置样式,直接加上主题样式
appElement.setAttribute('class', klass_name);
} else {
// 已经设置样式
const klass_list = klass_content.split(' ');
const arr = [];
// 遍历已有的样式,移除和主题有关的样式类
klass_list.forEach(item => {
if (item) {
if (item.indexOf('theme-') === 0) {
// 已有的主题类需要移除
const pre_active_theme_name = item.replace('theme-', '');
const pre_active_theme_data = theme_map[pre_active_theme_name];
pre_active_theme_data.is_active = false;
} else {
arr.push(item);
}
}
});
// 添加新的主题样式类
arr.push(klass_name);
theme_data.is_active = true;
const klass_value = arr.join(' ');
// 设置class属性
appElement.setAttribute('class', klass_value);
}
} else {
}
}
6.在theme-dark.less,theme-dark.css,theme-light.css,theme-light.less书写样式