APP后端切换主题
1.后端切换主题的好处或目的
1、集中管理主题样式,便于维护和更新。
2、根据用户的个人偏好或系统设置,动态提供合适的主题。
2.步骤
1、后端提供一个 API 接口,返回当前用户或系统的主题配置,包括主题名称和样式。
{
"theme": "dark",
"styles": {
"--background-color": "#000000",
"--text-color": "#ffffff",
"--button-bg-color": "#333333",
"--button-text-color": "#ffffff"
}
}
2、在 store.js 中配置 Vuex,用于管理全局的主题状态和样式数据。
import axios from 'axios';
const state = {
theme: 'light',
styles: {}
}
const mutations = {
SET_THEME(state, theme) {
state.theme = theme;
},
SET_STYLES(state, styles) {
state.styles = styles;
}
}
const actions = {
async fetchTheme({ commit }) {
try {
const response = await axios.get('/api/theme');
commit('SET_THEME', response.data.theme);
commit('SET_STYLES', response.data.styles);
} catch (error) {
console.error('Failed to fetch theme:', error);
}
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
3、在 App.vue 中初始化 Vuex,并在应用启动时获取主题数据存储到vuex。
created() {
this.$store.dispatch('theme/fetchTheme')
},
4、在组件中通过 计算属性设置
<view :style="containerStyle"></view>
computed: {
containerStyle() {
const myStyle = {
backgroundColor: this.$store.getters.theme['--background-color'],
color: this.$store.getters.theme['--text-color'],
borderBottom: `1px solid ${this.$store.getters.theme['--text-color']}`
}
return myStyle
}
}
5、可以创建一个mixin混入使用
export default {
computed: {
backgroundColor() {
return {
backgroundColor: this.$store.getters.theme['--button-bg-color']
}
},
borderBottom() {
return {
borderBottom: `1px solid ${this.$store.getters.theme['--background-color']}`
}
}
}
}
//最好是一个类型弄一个计算属性
6、注入页面使用
<view :style="{...borderBottom, ...backgroundColor}">11111</view>
//使用多个的话就用解构
import themeMixin from '@/mixin/theme';
export default {
mixins:[mixins, themeMixin]
}
3.难点
- 后端需要提供一个稳定、快速的 API 接口。
- 前端在应用启动时,需要异步获取主题数据并更新全局状态,处理异步请求的结果和错误。
- 动态加载并应用后端返回的 CSS 变量,确保整个应用中的样式及时更新,现在app已经完成所有的样式 要找到所有需要修改的地方,查找对应的图标并且把以前需要用icon图标却用了图片的地方修改掉。
- 需要在每个页面都写计算属性动态添加css