vue2 scss主题切换
1.定义scss全局变量
//@/assets/css/theme.scss
$primaryColor: var(--primaryColor);
$primaryTextColor: var(--primaryTextColor);
2.定义样式表
export default {
default: {
primaryColor: "#000",
primaryTextColor: "green",
},
my: {
primaryColor: "skyblue",
primaryTextColor: "yellow",
},
};
3.新增主题模块
import themes from "@/lib/theme";
const changeStyle = (themeObj) => {
Object.keys(themeObj).forEach((item) => {
document
.getElementsByTagName("body")[0]
.style.setProperty(`--${item}`, themeObj[item]);
});
};
export const setTheme = (themeName) => {
localStorage.setItem("theme", themeName);
const themeConfig = themes[themeName];
changeStyle(themeConfig);
};
export const initTheme = () => {
const themeName = localStorage.getItem("theme");
if (themeName) {
setTheme(themeName);
} else {
setTheme("default");
}
};
4.使用
import Vue from "vue";
import App from "./App.vue";
import { initTheme } from "@/module/theme";
Vue.config.productionTip = false;
new Vue({
render: (h) => h(App),
}).$mount("#app");
initTheme();
//test.vue
<template>
<div>
<div class="box">你好,世界</div>
<button @click="setTheme('default')">默认样式</button>
<button @click="setTheme('my')">我的样式</button>
</div>
</template>
<script>
import { setTheme } from "@/module/theme";
export default {
methods: {
setTheme(themeName) {
setTheme(themeName);
},
},
};
</script>
<style lang="scss" scoped>
@import "~@/assets/css/theme.scss";
.box {
width: 200px;
height: 200px;
color: $primaryTextColor;
background-color: $primaryColor;
}
</style>