在uni-app中实现主题切换功能,可以使用vuex状态管理,具体实现如下:
- 安装vuex插件:
npm install vuex
- 创建vuex的store:
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
theme: 'light'
},
mutations: {
changeTheme(state, theme) {
state.theme = theme
}
}
})
export default store
- 在main.js中注册store:
import store from './store'
new Vue({
store,
...
})
- 在需要切换主题的组件中触发vuex的mutation:
<template>
<view class="container">
<button @click="changeTheme('light')">切换到浅色主题</button>
<button @click="changeTheme('dark')">切换到深色主题</button>
</view>
</template>
<script>
export default {
methods: {
changeTheme(theme) {
this.$store.commit('changeTheme', theme)
}
}
}
</script>
- 在根组件app.vue中根据vuex的状态更新主题样式:
<template>
<view
class="container"
:class="{
'light-theme': theme === 'light',
'dark-theme': theme === 'dark'
}"
>
<router-view />
</view>
</template>
<script>
export default {
computed: {
theme() {
return this.$store.state.theme
}
}
}
</script>
<style>
.light-theme {
background-color: #fff;
color: #333;
}
.dark-theme {
background-color: #333;
color: #fff;
}
</style>