基于uniapp+vuex实现的切换任意主题功能,基本测试没有问题,下面记录一下实现步骤及原理
1.根据自己的需求创建scss文件,下面贴一下代码
我这里是放在common/css/theme.scss文件中
.CyanTheme{
.bgColor{
background-color: #e6fbf3
}
.textColor{
color: #999999;
}
.textThColor{
color:#24ba97;
}
.borderColor{
border-color: #ccf7e7;
}
}
.DarkTheme{
.bgColor{
background-color: #292929
}
.textColor{
color: #fff;
}
.textThColor{
color:#ccf7e7;
}
.borderColor{
border-color: #000;
}
}
2.在app.vue中引入自定义的scss
<style lang="scss">
/*每个页面公共css */
@import '@/common/css/theme.scss';
</style>
3.vuex进行全局调用处理,引用你们自己封装的vuex方法
//基于自己的vuex使用方式将字段加入,默认给一个主题色,为了下次启动应用主题色不被重置最好做持久化储存处理,我这里是会存到本地数据的
vuex_theme: $theme.vuex_theme || 'CyanTheme' //主题色
4.页面中使用及切换方法
我这里只做演示,没有封装处理,你们可以自行处理一下
将每个页面的最外层元素加上vuex内的主题名称 :class="vk.getVuex('$theme.vuex_theme')",
内部元素的css会根据scss的外层类名进行相应的展示,所以只需要更改最外层的类型就能实现主题动态切换,当然要使用之前定义好的全局类名
<template>
<view class="container" :class="vk.getVuex('$theme.vuex_theme')">
<view class="textColor bgColor" @click="theme">本项目已包含uni
ui组件,无需import和注册,可直接使用。在代码区键入字母u,即可通过代码助手列出所有可用组件。光标置于组件名称处按F1,即可查看组件文档。</view>
</view>
</template>
data() {
return {
href: 'https://uniapp.dcloud.io/component/README?id=uniui',
themeType: 1
}
},
methods: {
theme() {
//这里只做演示,死数据,根据自己代码更改
if (this.themeType === 1) {
console.log(111);
this.themeType = 2;
vk.setVuex('$theme.vuex_theme', 'DarkTheme');
uni.setTabBarStyle({
color: '#ddd',
selectedColor: '#fff',
backgroundColor: '#111',
borderStyle: '#000'
})
} else {
this.themeType = 1;
vk.setVuex('$theme.vuex_theme', 'CyanTheme');
uni.setTabBarStyle({
color: '#696969',
selectedColor: '#111',
backgroundColor: '#ccf7e7',
borderStyle: '#24ba97'
})
}
}
}
贴一下gif图