包版本:
vite.config.js:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
css: {
preprocessorOptions: {
less: {
modifyVars: {
hack: `true; @import (reference) "${resolve('src/theme/style.less')}";`,
},
javascriptEnabled: true
}
}
},
})
/src/theme/style.less
// 默认的主题颜色
@primaryColor: var(--primaryColor, #000);
@primaryTextColor: var(--primaryTextColor, green);
// 导出变量
:export {
name: "less";
primaryColor: @primaryColor;
primaryTextColor: @primaryTextColor;
}
/src/theme/model.js
export const themes = {
default: {
primaryColor: `${74}, ${144},${226}`,
primaryTextColor: `${74}, ${144},${226}`,
},
dark: {
primaryColor: `${0},${0},${0}`,
primaryTextColor: `${0},${0},${0}`,
},
};
/src/theme/theme.js
import { themes } from "./model";
// 修改页面中的样式变量值
const changeStyle = (obj) => {
for (let key in obj) {
document
.getElementsByTagName("body")[0]
.style.setProperty(`--${key}`, obj[key]);
}
};
// 改变主题的方法
export const setTheme = (themeName) => {
localStorage.setItem("theme", themeName); // 保存主题到本地,下次进入使用该主题
const themeConfig = themes[themeName];
// 如果有主题名称,那么则采用我们定义的主题
if (themeConfig) {
localStorage.setItem("primaryColor", themeConfig.primaryColor); // 保存主题色到本地
localStorage.setItem("primaryTextColor", themeConfig.primaryTextColor); // 保存文字颜色到本地
changeStyle(themeConfig); // 改变样式
} else {
let themeConfig = {
primaryColor: localStorage.getItem("primaryColor"),
primaryTextColor: localStorage.getItem("primaryTextColor"),
};
changeStyle(themeConfig);
}
};
组件中css使用:
background: rgba(@primaryColor, 1);
color: @primaryTextColor;
JS切换主题:
import { setTheme } from "../theme/theme";
//调用切换方法
setTheme("default");
// 更改为自定义主题
custom() {
let newColor = {
r: 12,
g: 33,
b: 234,
};
let newPrimaryColor = `${newColor.r},${newColor.g},${newColor.b}`;
localStorage.setItem("primaryColor", newPrimaryColor); // 将新的主题色存入本地
setTheme();
},
参考:
https://zhuanlan.zhihu.com/p/440387917
https://blog.youkuaiyun.com/LiuJia20010827/article/details/127235713
https://blog.youkuaiyun.com/V_AYA_V/article/details/117783527