场景:动态加载路由,点击菜单路由跳转正常,但刷新页面报404
原因:使用404做异常路由捕获
刷新页面会导致路由丢失,重建路由时先加载了静态路由(包含异常路由捕获404),此时动态路由还未加载完成,url没有匹配到指定路由被划到404了
解决方法:抽离出404路由,按需添加
1、在router的onReady方法中判断用户登录状态,用户未登录则添加404路由,确保未登录时访问异常地址能跳转到404
2、在router的beforeEach方法中判断用户是否登录,登录成功获取用户信息后添加404路由,避免重复添加404
// 抽离出404路由
export const errorRoutes = [
{
name: 'NotFound',
path: '/:pathMatch(.*)*',
component: ''
}
]
router.onReady(() => {
if (!isLogin()){
// 未登录添加404路由
router.addRoutes(errorRoutes);
}
})
router.beforeEach((to, from, next) => {
if (isLogin()) {
if (store.state.user.menus.length === 0) {
store.dispatch('user/fetchUserInfo')
.then((routes) => {
// 登录后添加404路由
router.addRoutes(routes);
router.addRoutes(errorRoutes);
})
}
}
})