- 使用vuex,在store中存一个默认值和切换的方法
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
theme:'白'
},
getters: {
},
mutations: {
increment (state) {
if(state.theme == '黑'){
state.theme = '白'
}else if(state.theme == '白'){
state.theme = '黑'
}
}
},
actions: {
},
modules: {
}
})
在组件中使用
<template>
<div class="hello">
测试文本
<el-button @click="vuexx()">切换颜色</el-button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
created(){
this.vuexx();
},
methods:{
vuexx(){
this.$store.commit('increment') // 触发Vuex方法
if(this.$store.state.theme == '黑'){
document.documentElement.style.setProperty('--theme-background', 'black');
document.documentElement.style.setProperty('--theme-color', 'red');
}else if(this.$store.state.theme == '白'){
document.documentElement.style.setProperty('--theme-background', 'red');
document.documentElement.style.setProperty('--theme-color', '#fff');
}
}
}
}
</script>
<style>
:root {
--theme-color:#fff;
--theme-background: black; /* 默认主题颜色值 */
}
.hello{
height:100%;
width: 100%;
color: var(--theme-color);
background: var(--theme-background);
}
</style>