o
orangeed
V1
2023/03/22阅读:74主题:自定义主题1
vue | 动态路由刷新空白
解决在vue3中添加动态路由后,刷新页面空白,并且提示没有正确的路径。
问题
-
页面空白 -
控制台提示错误
解决过程
-
在 router.beforeEach
的第一行打印to
。 -
发现 to.matched.length
为1,仅仅包含了没有动态添加的路由,那么跳转的目标页面是没有的。 -
同时 to
的打印信息是后于warn
的,说明路由在挂载的时候已经初始化完毕了,这个时候的路由都没来得及添加上去,已经去跳转了。 -
得出结论,如果将动态路由提前添加好,然后才挂载上去,这样才能跳转到目标路由。
代码
在permission.ts
中封装一个添加路由的函数。
export const initRouter = async () => {
const res = await store.dispatch("permission/generateRoutes")
res.forEach((route: any) => {
router.addRoute(route)
})
}
在main.ts
文件中引入使用。
const boot = async () => {
await initRouter()
app.use(router).use(store).use(Directives).mount("#app")
}
boot()
注意
-
请务必使用 async
和await
去等待路由挂载完毕。 -
网上有很多的方案,但是基本上会有各种问题,比如,判断 to.match.length
是否为0,为0则去from.path
,否则去to.path
,这会出现刷新返回上一个页面的问题。比如,使用next({...to,replace:true})
,会死循环,因为找不到路由,会一直去to.path
,一直去next
。
作者介绍
o
orangeed
V1