我使用pinia管理登陆状态token,这是我的代码
import { defineStore } from 'pinia';
import { ref } from "vue"
import { resetRouter } from "@/router"
import { setToken as _setToken, getToken, removeToken, setToken } from "@/common/utils/cache/cookies"
export const useUserStore = defineStore('user', {
state: () => ({
token: getToken() || "",
username: "",
rolename: "",
roles: {},
loginSuccess: false,
}),
actions: {
//设置登录成功
changeLoginSuccess(val: boolean) {
this.loginSuccess = val;
},
//获取用户详情
getInfo(){
},
setToken(token: string) {
this.token = token;
_setToken(token);
},
// 重置Token
resetToken() {
removeToken()
this.token = ""
},
// 退出登录
logout() {
removeToken()
this.token = ""
this.username = ""
this.rolename = ""
this.roles = {}
resetRouter()
},
},
});
我如果调用logout退出登陆后,然后在router前置路由守卫获取token判断是否登录,获取的token为什么还是有值的。
这是router代码
//前置守卫
router.beforeEach((to, from, next) => {
const userStore = useUserStore()
console.log(userStore.token)
if (userStore.token) {
if (to.name === 'login') {
next({ name: 'home' })
} else {
next()
}
} else {
if (to.name !== 'login') {
next({ name: 'login' })
} else {
next()
}
}
NProgress.start()
})
看看..................
建议改进一下排版,支持markdown语法
– dudu 6天前