SocialNetworks_duan/src/store/authentication/index.js

34 lines
930 B
JavaScript
Raw Normal View History

2025-08-14 13:33:15 +08:00
import { defineStore } from "pinia"
2025-08-15 14:40:59 +08:00
import { login, refreshToken } from "@/service/api/authentication"
2025-08-14 16:05:58 +08:00
import cache from "@/utils/cache"
import router from "@/router"
2025-08-14 14:42:11 +08:00
import { ElMessage } from "element-plus"
2025-08-14 13:33:15 +08:00
export const useLoginStore = defineStore("loginStore", {
state: () => ({
2025-08-15 14:40:59 +08:00
token: cache.getItem("token") ?? ""
2025-08-14 13:33:15 +08:00
}),
2025-08-14 14:42:11 +08:00
actions: {
2025-08-15 14:40:59 +08:00
setToken(accessToken) {
this.token = accessToken
cache.setItem("token", accessToken)
},
2025-08-14 14:42:11 +08:00
async loginForAccessToken(userInfo) {
const res = await login(userInfo)
2025-08-14 16:05:58 +08:00
if (res.code != 200) return
2025-08-15 14:40:59 +08:00
this.setToken(res.data.accessToken)
2025-08-14 16:05:58 +08:00
ElMessage.success("登录成功!")
router.push("/navigation")
2025-08-15 14:40:59 +08:00
},
async loginForRefreshToken() {
const res = await refreshToken()
if (res.code == 200) {
this.setToken(res.data.accessToken)
return true // 刷新成功
} else {
return false
}
2025-08-14 14:42:11 +08:00
}
}
2025-08-14 13:33:15 +08:00
})