// stores/user.ts import { defineStore } from 'pinia' import { setAuthToken, clearAuthToken } from '@/utils/auth' import type { IUserInfo } from '@/types/user' export const useUserStore = defineStore('user', { state: (): IUserInfo => ({ id: 0, name: '', avatar: '', email: '', phone: '', token: uni.getStorageSync('token') || '', }), getters: { isLoggedIn: (state: any) => Boolean(state.token), userInfo: (state: any) => { const { id, name, avatar, email, phone } = state return { id, name, avatar, email, phone } }, }, actions: { /** 设置用户信息(登录成功后调用) */ setUserInfo(userInfo: IUserInfo) { Object.assign(this, userInfo) if (userInfo.token) { this.token = userInfo.token setAuthToken(userInfo.token) } uni.setStorageSync('userInfo', userInfo) }, /** 登出 */ logout() { try { // ✅ 优先使用 Pinia 内置方法(最安全) this.$reset() } catch (err) { // ✅ 如果 $reset 不存在(旧版 pinia),动态清空 Object.keys(this).forEach((key) => { // TS安全地访问 this[key] const val = (this as Record)[key] if (typeof val === 'string') (this as any)[key] = '' else if (typeof val === 'number') (this as any)[key] = 0 else if (Array.isArray(val)) (this as any)[key] = [] else if (typeof val === 'object' && val !== null) (this as any)[key] = {} else (this as any)[key] = undefined }) } clearAuthToken() uni.removeStorageSync('userInfo') uni.reLaunch({ url: '/pages/user/login' }) }, /** 从本地存储恢复用户信息 */ restoreUserInfo() { const userInfo = uni.getStorageSync('userInfo') if (userInfo) Object.assign(this, userInfo) const token = uni.getStorageSync('token') if (token) this.token = token }, }, })