vue 项目切换主题颜色

vue 项目切换主题颜色

参考地址:https://github.com/LiuyangAce/theme-switch/tree/master

1,在public/style文件夹下,创建主题文件

  • theme-dark.css
:root {
	--theme-color: #06142a;
	--bg-color: #06142a;
	--font-color: #ffffff;
}
/* el输入框的样式 */
.el-input__inner {
  background-color: #141414 !important;
}
  • theme-light.css
:root {
	--theme-color: #ffffff;
	--bg-color: #ffffff;
	--font-color: #000000;
}

/* el输入框的样式 */
.el-input__inner {
  background-color: #ffffff !important;
}

2,在public/index.html文件中,引入默认主题文件

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>air-conditioner</title>
	<!-- 导入默认颜色的css文件(这里是light) -->
    <link
      id="theme-link"
      rel="stylesheet"
      type="text/css"
      href="./static/style/theme-light.css"
    />
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

3, 配置vuex

  • store/index.js
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    theme: "light",
  },
  mutations: {
    // 设置切换主题
    setTheme(state, theme) {
      state.theme = theme;
      localStorage.setItem("current-theme", theme);
      document.head
        .querySelector("#theme-link")
        .setAttribute("href", `./style/theme-${theme}.css`);
    },
    //获取缓存主题
    getTheme(state) {
      state.theme = localStorage.getItem("current-theme") || "light";
      document.head
        .querySelector("#theme-link")
        .setAttribute("href", `./style/theme-${state.theme}.css`);
    }
  }
});

4, App.vue配置动画过渡

<script>
export default {
  name: "App",
  created() {
    this.$store.commit("getTheme");		/*加载上次退出是选择的主题*/
  }
};
</script>
<style>
* {
  transition: all 0.2s ease-out;
}
.el-input__inner {
  transition: all 0.2s ease-out;/*必须单独添加,不然el-input的组件过渡效果不能生效*/
}
</style>

5, 项目中的css颜色值取变量

<style scoped>
.btn {
  width: 100px;
  height: 100px;
  background-color: var(--bg-color);/*取背景的颜色变量*/
  color: var(--font-color);		/*取文字的颜色变量*/
}
</style>

6, 按钮切换颜色

<template>
  <div class="hello">
    <button @click="switchTheme">切换主题</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
     index: 0,
    };
  },
  methods: {
    switchTheme() {
      if(this.index % 2 == 0){
        this.$store.commit("setTheme", 'dark');
      }else{
        this.$store.commit("setTheme", 'light');
      }
      this.index++
    }
  }
};
</script>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值