目前是开发环境,history模式,有个index.vue的主页加了路由组件<RouterView/>,在路由导航守卫中向这个页面动态加了子路由,点击菜单的时候,跳转到了对应页面,但刷新后会打到404页面,后面发现是加了这个导致的“path: "/:catchAll(.*)",redirect: '/404',” 如果不加则正常,但是控制台会出现警告[Vue Router warn]: No match found for location with path,而且如果url输入一个不存在的路径也不会跳转到404了
index.vue
<el-container>
<el-header style="padding: 0;height: 100px">
<Header></Header>
</el-header>
<el-main>
<RouterView/>
</el-main>
<el-footer>Footer</el-footer>
</el-container>
const createBaseRouter = () => createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{path: '/', redirect: '/login'},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/index',
name: 'Index',
component: Index,
children: []
},
{
path: '/404',
// name: '404',
component: () => import('@/components/error/404.vue')
},
{
path: '/401',
name: '401',
component: () => import('@/components/error/401.vue')
},
{
// vue2使用* vue3使用:pathMatch('*') 或者 :pathMatch('*')* 或者 :catchAll(.*)
path: "/:catchAll(.*)",
redirect: '/404',
}
]
})
// 路由前置守卫
router.beforeEach( (to, from, next) => {
if (to.path === '/login') return next();
let token = getToken();
if (!token) {
return next('/login');
} else {
if (Object.keys(useUserStore().userInfo).length === 0) {//如果没有用户,则获取用户信息
getUserInfo().then(res => {
useUserStore().setUserInfo(res.data)
useUserStore().setPerms(res.data.permsList)
useUserStore().setMenuTreeList(res.data.menuTreeList)
const routes = router.getRoutes()
let indexRoute: any = routes.find(r => r.name === 'Index')
const dynamicsRoutes = filterAsyncRouter(res.data.menuTreeList)
// 添加路由
indexRoute.children = indexRoute.children.concat(dynamicsRoutes);
router.addRoute(indexRoute)
console.log(router.getRoutes());
next({...to, replace: true});
}).catch((e) => {
ElMessage.error(e.message);
});
} else {
next();
}
}
})
不要重定向到404,写成下面试试