87 lines
1.9 KiB
JavaScript
87 lines
1.9 KiB
JavaScript
import { defineStore } from 'pinia'
|
|
import { ref, computed } from 'vue'
|
|
import { setStorage, getStorage, removeStorage, TOKEN_KEY } from '../utils/storage.js'
|
|
import * as userApi from '../api/user.js'
|
|
|
|
export const useUserStore = defineStore('user', () => {
|
|
const token = ref(getStorage(TOKEN_KEY) || null)
|
|
const userInfo = ref(null)
|
|
|
|
// 计算属性:是否已登录
|
|
const isLoggedIn = computed(() => !!token.value)
|
|
|
|
/**
|
|
* 登录(含协议勾选校验)
|
|
* @param {string} phone - 手机号
|
|
* @param {string} code - 验证码
|
|
* @param {string} areaCode - 区号
|
|
* @param {boolean} agreedToTerms - 是否已勾选协议
|
|
*/
|
|
async function login(phone, code, areaCode, agreedToTerms) {
|
|
if (!agreedToTerms) {
|
|
uni.showToast({ title: '请阅读并同意协议', icon: 'none' })
|
|
return Promise.reject(new Error('未同意协议'))
|
|
}
|
|
|
|
const res = await userApi.login(phone, code, areaCode)
|
|
const newToken = res.data?.token || res.data
|
|
token.value = newToken
|
|
setStorage(TOKEN_KEY, newToken)
|
|
// 登录成功后立即获取用户信息
|
|
try {
|
|
await fetchUserInfo()
|
|
} catch (e) {}
|
|
return res
|
|
}
|
|
|
|
/**
|
|
* 获取用户信息
|
|
*/
|
|
async function fetchUserInfo() {
|
|
const res = await userApi.getUserInfo()
|
|
userInfo.value = res.data
|
|
return res
|
|
}
|
|
|
|
/**
|
|
* 退出登录
|
|
*/
|
|
async function logout() {
|
|
try {
|
|
await userApi.logout()
|
|
} catch (e) {
|
|
// 即使API调用失败也清除本地状态
|
|
}
|
|
clearAuth()
|
|
}
|
|
|
|
/**
|
|
* 注销账号
|
|
*/
|
|
async function deleteAccount() {
|
|
const res = await userApi.deleteAccount()
|
|
clearAuth()
|
|
return res
|
|
}
|
|
|
|
/**
|
|
* 清除本地认证信息
|
|
*/
|
|
function clearAuth() {
|
|
token.value = null
|
|
userInfo.value = null
|
|
removeStorage(TOKEN_KEY)
|
|
}
|
|
|
|
return {
|
|
token,
|
|
userInfo,
|
|
isLoggedIn,
|
|
login,
|
|
fetchUserInfo,
|
|
logout,
|
|
deleteAccount,
|
|
clearAuth
|
|
}
|
|
})
|