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>