关于性能
来源:8-7 路由和权限校验逻辑梳理和总结

慕先生5461412
2021-11-08
这里每次切换路由都会对路由表做一次深度遍历,路由多的画是否会影响性能呢?为什么不只在登录之后设定一次路由权限呢?
router.beforeEach(async(to, from, next) => {
// start progress bar,顶部进度条
NProgress.start()
// set page title
document.title = getPageTitle(to.meta.title)
// determine whether the user has logged in
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
// if is logged in, redirect to the home page
next({ path: '/' })
NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
} else {
// determine whether the user has obtained his permission roles through getInfo
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {
next()
} else {
try {
// get user info
// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
const { roles } = await store.dispatch('user/getInfo')
// generate accessible routes map based on roles
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
// dynamically add accessible routes
router.addRoutes(accessRoutes)
// hack method to ensure that addRoutes is complete
// set the replace: true, so the navigation will not leave a history record
next({ ...to, replace: true })
} catch (error) {
// remove token and go to login page to re-login
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
next()
} else {
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
写回答
1回答
-
扬_灵
2021-11-08
同学你好,这个是为了防止用于直接通过路由地址进入才在路由前置守卫中对权限进行判断的。这里的路由信息是固定的后面可以使用动态路由,登录时根据用户登录信息获取到路由权限传递给前端,前端这边可以根据路由信息进行渲染就方便了。
00
相似问题