OMS_H5/src/store/auth.ts

88 lines
2.5 KiB
TypeScript
Raw Normal View History

import { defineStore } from 'pinia'
import { login, logout as logoutApi } from '@/api/auth'
import type { LoginParams } from '@/types'
interface AuthState {
token: string | null
userInfo: any | null
isAuthenticated: boolean
}
export const useAuthStore = defineStore('auth', {
state: (): AuthState => ({
token: null,
userInfo: null,
isAuthenticated: localStorage.getItem('isAuthenticated') === 'true'
}),
actions: {
/**
*
*/
async login(params: LoginParams) {
try {
// 调用登录接口
const response = await login(params)
// 检查响应状态
if (response.status === 200 && response.data.code === 0) {
// 由于服务器使用session判断登录状态我们只需要设置认证状态为true
this.isAuthenticated = true
// 保存到localStorage用于页面刷新后保持登录状态
localStorage.setItem('isAuthenticated', 'true')
// 如果选择了记住密码,则保存用户名和密码
if (params.rememberMe) {
localStorage.setItem('savedUsername', params.username)
localStorage.setItem('savedPassword', params.password)
} else {
// 清除保存的用户名和密码
localStorage.removeItem('savedUsername')
localStorage.removeItem('savedPassword')
}
return response.data
} else {
throw new Error(response.data.msg || '登录失败')
}
} catch (error: any) {
console.error('登录接口调用失败:', error)
throw error
}
},
/**
*
*/
async logout() {
try {
// 调用后端logout接口清除session
await logoutApi()
} catch (error) {
console.warn('服务器退出登录失败,仅清除本地状态:', error)
} finally {
// 清除本地状态
this.token = null
this.userInfo = null
this.isAuthenticated = false
// 清除localStorage中的认证状态
localStorage.removeItem('isAuthenticated')
// 注意:这里不清除保存的用户名和密码,以便下次自动填充
}
},
/**
*
*/
checkAuthStatus() {
// 从localStorage检查认证状态
const isAuthenticated = localStorage.getItem('isAuthenticated')
if (isAuthenticated === 'true') {
this.isAuthenticated = true
}
}
}
})