vue-router 使用动态路由,刷新页面后页面是空白
版本
添加动态路由
export const actions: ActionTree<permission_state.permission_info, vuex.RootStore> & Actions = {
async [PermissionActionsType.GET_PERMISSIONS](
{commit}: AugmentedActionContext,
) {
await api.get_permission({}).then(async (res: any) => {
const routers = filter_router(res.permissions)
for (const rou of routers) {
if (!router.hasRoute((rou.name as RouteRecordName))) router.addRoute((rou.name as RouteRecordName), rou)
}
router['routers'] = routers
commit(PERMISSION_TYPES.SET_ROUTERS, routers)
})
}
}
前置守卫
router.beforeEach(async (to: RouteLocationNormalized, _: RouteLocationNormalized, next: NavigationGuardNext) => {
NProgress.start()
const store = useStore()
if (store.state.user.token) {
await store.dispatch(PermissionActionsType.GET_PERMISSIONS, undefined)
if (to.path === '/login') {
next({path: '/index'})
} else {
await next()
}
NProgress.done()
} else {
// next()
// NProgress.done()
// // Has no token
if (whiteList.indexOf(to.path) !== -1) {
// In the free login whitelist, go directly
next()
NProgress.done()
} else {
// Other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
出现原因
因为我们刷新页面的时候,还是在之前页面,就不会触发新的导航,所以就不会显示。
解决方法
不使用next使用router.push()方法
router.beforeEach(async (to: RouteLocationNormalized, _: RouteLocationNormalized, next: NavigationGuardNext) => {
NProgress.start()
const store = useStore()
if (store.state.user.token) {
await store.dispatch(PermissionActionsType.GET_PERMISSIONS, undefined)
if (to.path === '/login') {
next({path: '/index'})
} else {
// 判断是不是当前页面,如果是当前页面就使用push方法,就OK了。
if (!to.meta.title) await router.push({path: to.path})
await next()
}
NProgress.done()
} else {
// next()
// NProgress.done()
// // Has no token
if (whiteList.indexOf(to.path) !== -1) {
// In the free login whitelist, go directly
next()
NProgress.done()
} else {
// Other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})