user.js 1.5 KB
Newer Older
芊里 已提交
1
// 上次启动时的用户信息
DCloud_JSON's avatar
DCloud_JSON 已提交
2
let userInfoHistory = uni.getStorageSync('userInfo') || {};
芊里 已提交
3
let state = {
DCloud_JSON's avatar
DCloud_JSON 已提交
4
		//是否已经登录
DCloud_JSON's avatar
DCloud_JSON 已提交
5 6 7
		hasLogin: Boolean(Object.keys(userInfoHistory).length),
		//用户信息
		info: userInfoHistory
芊里 已提交
8 9 10 11 12 13 14 15 16 17
	},
	getters = {
		info(state) {
			return state.info;
		},
		hasLogin(state){
			return state.hasLogin;
		}
	},
	mutations = {
DCloud_JSON's avatar
DCloud_JSON 已提交
18
		login(state, info) { //登录成功后的操作
DCloud_JSON's avatar
DCloud_JSON 已提交
19
			//原有的结合传来的参数
芊里 已提交
20 21
			let _info = state.info;
			state.info = Object.assign({}, _info, info);
DCloud_JSON's avatar
DCloud_JSON 已提交
22
			//设置为已经登录
芊里 已提交
23
			state.hasLogin = true;
24
			console.log('state.info',state.info);
DCloud_JSON's avatar
DCloud_JSON 已提交
25
			//存储最新的用户数据到本地持久化存储
26
			uni.setStorageSync('userInfo', state.info);
27 28 29 30 31 32 33 34 35 36
			if(info.token){
				uni.setStorage({
					key: 'uni_id_token',
					data: state.info.token,
					complete(e){
						// console.log('setStorage-------',e);
					}
				});
				uni.setStorageSync('uni_id_token_expired', state.info.tokenExpired)
			}
芊里 已提交
37 38
		},
		logout(state) {
39
			state.info = {};
芊里 已提交
40
			state.hasLogin = false;
41
			uni.setStorageSync('userInfo', {});
42
			uni.removeStorageSync('uni_id_token');
43
			uni.setStorageSync('uni_id_token_expired', 0)
芊里 已提交
44 45 46
		}
	},
	actions = {
47 48 49 50 51 52 53 54 55 56 57 58
		logout(context){
			uni.showLoading({mask:true})
			uniCloud.callFunction({
				name:'uni-id-cf',
				data:{action:'logout'},
				complete: (e) => {
					console.log(e);
					context.commit('logout')
					uni.hideLoading()
				}
			})
		}
芊里 已提交
59 60
	}
export default {
DCloud_JSON's avatar
DCloud_JSON 已提交
61
	namespaced: true,
芊里 已提交
62 63 64 65
	state,
	getters,
	mutations,
	actions
66
}