思路来源:https://ext.dcloud.net.cn/plugin?id=6215
源码demo:https://github.com/zqy233/uniapp-theme-switch
思路:
style='--theme-color: #fff";'这种写法绑定var变量字符串,再基于vuex和mixin简化写法改变
https://juejin.cn/post/6937530846471520287
设置主题后,获取相应主题的var变量字符串
import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({state: {themeName: "light",themeStyle: {"light": `--nav-bg:#42b983;--nav-color:#ffffff;`,"dark": `--nav-bg:#000;--nav-color:#ffffff;`}},getters: {theme(state) {return state.themeStyle[state.themeName]}},mutations: {setTheme(state, themeName = "light") {state.themeName = themeName}}
})export default store
每个页面都需要获取相应主题的var变量字符串,使用mixin进行简化写法
import {mapState,mapGetters
} from 'vuex'
export default {install(Vue) {Vue.mixin({computed: {...mapState({themeName: 'themeName'}),...mapGetters({theme: "theme"})}})}
}
import Vue from 'vue'
import App from './App'
import store from './store'
import mixin from '@/mixin/themeMixin.js'
Vue.use(mixin)
Vue.config.productionTip = false
App.mpType = 'app'const app = new Vue({store,...App
})
app.$mount()
uni.scss加入代码
$nav-bg: var(--nav-bg);
$nav-color: var(--nav-color);
页面中使用var变量的写法
页面中使用scss变量的写法
下方这种写法不能正确切换主题,因为绑定的var变量字符串是绑定在页面最外层元素上的,而page层是页面最外层元素的祖先级(目前没找到办法,更改page层的var变量值)
只能使用这种写法
page {filter: grayscale(100%);
}