uniapp 后端切换主题

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.难点

  1. 后端需要提供一个稳定、快速的 API 接口。
  2. 前端在应用启动时,需要异步获取主题数据并更新全局状态,处理异步请求的结果和错误。
  3. 动态加载并应用后端返回的 CSS 变量,确保整个应用中的样式及时更新现在app已经完成所有样式 找到所有需要修改地方,查找对应的图标并且以前需要icon图标图片地方修改
  4. 需要每个页面计算属性动态添加css
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值