从0到1构建uniapp应用-store状态管理

419 阅读1分钟

背景

在 UniApp的开发中,状态管理的目标是确保应用数据的一致性,提升用户体验,并简化开发者的工作流程。通过合理的状态管理,可以有效地处理用户交互、数据同步和界面更新等问题。
此文主要用store来管理用户的登陆信息。

重要概念

1.  状态(State):状态代表了应用中数据的变化。在 UniApp Store 中,
     这可能包括用户信息、插件列表、购物车内容、交易详情等。
1.  动作(Action):动作是触发状态变化的操作。
     例如,用户点击购买按钮、更新插件信息或提交评分等行为都会产生相应的动作。

集成步骤

创建store目录

在目录下创建index.js文件,内容如下

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)


const store = new Vuex.Store({
	//仓库中共有属性的集合,用于存储公共状态,只存储
	state: {
		hasLogin: false,//公共属性
		userInfo: {} //公共属性
	},
	//vuex中mutations是专门用来修改state中属性状态的方法集合(对象)
	mutations: {
		login(state, provider) { //方法名随便起,参数state是固定写法
			state.hasLogin = true;
			state.userInfo = provider;
			
			//store 存储json数据格式的用户信息
			uni.setStorageSync('userInfo', provider);
			uni.setStorageSync('thorui_token', provider.token)
			
			if(provider.roleList != null && provider.roleList != undefined && provider.roleList.length > 0){
				uni.setStorageSync('roleList', provider.roleList);
			}
		},
		logout(state) {
			state.hasLogin = false;
			state.userInfo = {};
			uni.removeStorageSync('userInfo');
			uni.removeStorageSync('thorui_token');
			uni.removeStorageSync('roleList');
		}
	},
	actions: {
	
	},
	getters: {
		getUserInfo(state) {
			return state.userInfo
		}
	}
})

export default store

配置main.js

import store from './store'
Vue.prototype.store = store;

const app = new Vue({
  ...App,
  store
})

线上体验地址, 重点就是登陆部分的使用了store实现 mincode.jpg

相关state和mutations使用具体见
vuex之state-状态对象的获取方法