58 lines
1.2 KiB
JavaScript
58 lines
1.2 KiB
JavaScript
/**
|
|
* 用户状态管理
|
|
* 管理登录凭证、用户信息、登录状态
|
|
*/
|
|
import { defineStore } from 'pinia'
|
|
import { ref, computed } from 'vue'
|
|
import { clearAuth } from '../utils/request'
|
|
|
|
export const useUserStore = defineStore('user', () => {
|
|
// 状态
|
|
const token = ref(uni.getStorageSync('token') || '')
|
|
const userInfo = ref(JSON.parse(uni.getStorageSync('userInfo') || '{}'))
|
|
|
|
// 计算属性
|
|
const isLoggedIn = computed(() => !!token.value)
|
|
const userId = computed(() => userInfo.value?.id || null)
|
|
|
|
/**
|
|
* 设置登录信息
|
|
* @param {string} newToken - JWT token
|
|
* @param {Object} info - 用户信息
|
|
*/
|
|
function setLoginInfo(newToken, info) {
|
|
token.value = newToken
|
|
userInfo.value = info
|
|
uni.setStorageSync('token', newToken)
|
|
uni.setStorageSync('userInfo', JSON.stringify(info))
|
|
}
|
|
|
|
/**
|
|
* 退出登录
|
|
*/
|
|
function logout() {
|
|
token.value = ''
|
|
userInfo.value = {}
|
|
clearAuth()
|
|
uni.reLaunch({ url: '/pages/login/login' })
|
|
}
|
|
|
|
/**
|
|
* 检查登录状态
|
|
* @returns {boolean} 是否已登录
|
|
*/
|
|
function checkLogin() {
|
|
return isLoggedIn.value
|
|
}
|
|
|
|
return {
|
|
token,
|
|
userInfo,
|
|
isLoggedIn,
|
|
userId,
|
|
setLoginInfo,
|
|
logout,
|
|
checkLogin
|
|
}
|
|
})
|