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
<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>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值