vue2 scss主题切换

vue2 scss主题切换

1.定义scss全局变量

//@/assets/css/theme.scss
$primaryColor: var(--primaryColor);
$primaryTextColor: var(--primaryTextColor);

2.定义样式表

//@/lib/theme.scss
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.使用

//main.js
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




你可能感兴趣的:(scss,javascript,前端)