Use pinia for holding router state #595
-
I use vue3+vite+typescript for my project. As a beginner I want to use vue-router for routing my pages. const loginRoutePath = '/login'
const defaultRoutePath = '/'
const whiteList = ['login', 'register']
router.beforeEach(async(to,from)=>{
console.log(to)
const { getStatus, getUserInfo, doGetUser, setMenuList, generateRoutes, getMenubar, setToken } = useLayoutStore()
... //others code
if(getMenubar.menuList.length === 0) {
await generateRoutes()
console.log(getUserInfo)
console.log(getMenubar.menuList)
return to.fullPath
}
}) Here is the code about the definition of pinia store export const useLayoutStore = defineStore({
id:'layout',
state:():ILayout => ({
menubar: {
menuList: [],
},
userInfo: {
name: '',
roles: {
permission:[]
}
},
status: {
isLoading: false,
ACCESS_TOKEN: ACCESS_TOKEN || ''
}
}),
getters: {
getMenubar():IMenubar {
return this.menubar
},
getUserInfo():IUserInfo {
return this.userInfo
},
getStatus():IStatus {
return this.status
}
},
actions: {
setToken(token:string):void {
this.status.ACCESS_TOKEN = token
setLocal('token', this.status, 1000 * 60 * 60)
},
async doLogin(loginParam: UmsAdminLoginParam) {
await login(loginParam).then(response => {
const { token } = response.data
if(token){
const { token } = response.data
this.setToken(token)
}else{
throw '用户名或密码错误'
}
})
},
async doGetUser():Promise<void> {
const res = await getUser()
const userInfo = res.data
this.userInfo = userInfo
},
async generateRoutes() {
await this.doGetUser()
const roles = this.userInfo.roles
const accessedRoutes = filterAsyncRouter(asyncRouterMap,roles)
accessedRoutes.forEach((r:any) => {
console.error('addRoute')
router.addRoute(r)
})
constantRouterMap.slice().reverse().forEach(r => {accessedRoutes.unshift(r)})
this.menubar.menuList = accessedRoutes
}
}
}) The code work for the time being. But I am comfused by 'getUserInfo' in 'beforeEach' logged as the value have already not set while it done in the 'doGetUser' action. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Since your action is async, you should await its completion inside of the router before each BTW, avoid destructuring a store, you don't get a reactive value, you get the value at the time of the destructuring and this could fail in some scenarios |
Beta Was this translation helpful? Give feedback.
Since your action is async, you should await its completion inside of the router before each
BTW, avoid destructuring a store, you don't get a reactive value, you get the value at the time of the destructuring and this could fail in some scenarios