|
|
|
|
import { defineStore } from 'pinia';
|
|
|
|
|
|
|
|
|
|
export const useUserStore = defineStore('user', {
|
|
|
|
|
state: () => ({
|
|
|
|
|
loginRes: uni.getStorageSync('loginRes') || null, // 存储登录响应数据
|
|
|
|
|
userInfo: uni.getStorageSync('userInfo') || null, // 用户信息
|
|
|
|
|
token: uni.getStorageSync('token') || null // 认证令牌
|
|
|
|
|
}),
|
|
|
|
|
|
|
|
|
|
getters: {
|
|
|
|
|
isLoggedIn: (state) => !!state.token,
|
|
|
|
|
userId: (state) => state.userInfo?.userId || null
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
actions: {
|
|
|
|
|
/**
|
|
|
|
|
* 设置登录响应数据
|
|
|
|
|
* @param {Object} data - 登录响应数据
|
|
|
|
|
*/
|
|
|
|
|
setLoginRes(data) {
|
|
|
|
|
this.loginRes = data;
|
|
|
|
|
uni.setStorageSync('loginRes', data);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 设置用户信息
|
|
|
|
|
* @param {Object} userInfo - 用户信息
|
|
|
|
|
*/
|
|
|
|
|
setUserInfo(userInfo) {
|
|
|
|
|
this.userInfo = userInfo;
|
|
|
|
|
uni.setStorageSync('userInfo', userInfo);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 设置认证令牌
|
|
|
|
|
* @param {String} token - 认证令牌
|
|
|
|
|
*/
|
|
|
|
|
setToken(token) {
|
|
|
|
|
this.token = token;
|
|
|
|
|
uni.setStorageSync('token', token);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 清除所有用户数据
|
|
|
|
|
*/
|
|
|
|
|
clearUserData() {
|
|
|
|
|
this.loginRes = null;
|
|
|
|
|
this.userInfo = null;
|
|
|
|
|
this.token = null;
|
|
|
|
|
uni.removeStorageSync('loginRes');
|
|
|
|
|
uni.removeStorageSync('userInfo');
|
|
|
|
|
uni.removeStorageSync('token');
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 更新用户信息
|
|
|
|
|
* @param {Object} updates - 要更新的用户信息字段
|
|
|
|
|
*/
|
|
|
|
|
updateUserInfo(updates) {
|
|
|
|
|
this.userInfo = { ...this.userInfo, ...updates };
|
|
|
|
|
uni.setStorageSync('userInfo', this.userInfo);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 更新单个用户信息字段
|
|
|
|
|
* @param {String} field - 要更新的字段名
|
|
|
|
|
* @param {*} value - 要更新的字段值
|
|
|
|
|
*/
|
|
|
|
|
updateUserInfoField(field, value) {
|
|
|
|
|
if (this.userInfo) {
|
|
|
|
|
this.userInfo = { ...this.userInfo, [field]: value };
|
|
|
|
|
} else {
|
|
|
|
|
this.userInfo = { [field]: value };
|
|
|
|
|
}
|
|
|
|
|
uni.setStorageSync('userInfo', this.userInfo);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|