从vue2项目转换为Vue3项目时,路由导航守卫中加载后端返回的动态路由,并配置未识别的路由自动跳转指定错误页面(如404页面)时,出现了
ue-router.mjs:1321 Uncaught (in promise) Error: Catch all routes ("*") must now be defined using a param with a custom regexp
的问题
Vue2中路由导航守卫中加载动态路由案例代码如下
let asyncRouter = []
// 路由导航守卫中,加载动态路由
router.beforeEach((to, from, next) => {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
const token = tokenStore.get('token')
if (token) {
dbApi.getRouter({}).then((response) => {
const res = response.data
asyncRouter = res.data
asyncRouter.push({
component: "error/404",
name: "404",
path: "*" //问题主要出现在这里
});
store.commit('setRouters', asyncRouter)
goTo(to, next,asyncRouter)
})
} else {
if (to.path === '/') {
next()
}
}
}
})
router.afterEach(() => {
//....
})
function goTo(to, next,asyncRouter) {
router.addRoutes(asyncRouter) //注意这里时Vue2中添加路由的方法,与Vue3有所区别
next({...to, replace: true})
}
let asyncRouter = []
// 路由导航守卫中,加载动态路由
router.beforeEach((to, from, next) => {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
const accountStore = useAccountStore();
const token = accountStore.token
if (token) {
dbApi.getRouter({}).then((response) => {
const res = response.data
asyncRouter = res.data
asyncRouter.push({
component: "error/404",
name: "404",
path: "*" //问题主要出现在这里
});
store.commit('setRouters', asyncRouter)
goTo(to, next,asyncRouter)
})
} else {
if (to.path === '/') {
next()
}
}
}
})
router.afterEach(() => {
//....
})
function goTo(to, next,asyncRouter) {
asyncRouter.forEach((route) => {
router.addRoute(route) //注意这里vue3添加路由方式,与Vue2有所区别
})
next({...to, replace: true})
}
详细信息如下
vue-router.mjs:1321 Uncaught (in promise) Error: Catch all routes ("*") must now be defined using a param with a custom regexp.
See more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.
at Object.addRoute (vue-router.mjs:1321:23)
at Object.addRoute (vue-router.mjs:2986:24)
at index.ts:119:16
at Array.forEach (<anonymous>)
at go (index.ts:117:17)
at index.ts:93:25
未识别的路由自动跳转指定错误页面(如404页面)时,将路由中的path配置
{ path: "*"}
改为{path: "/:catchAll(.*)"}
即可
asyncRouter.push({
component: "error/404",
name: "404",
path: "*"
});
asyncRouter.push({
component: "error/404",
name: "404",
path: "/:catchAll(.*)"
});
let asyncRouter = []
// 路由导航守卫中,加载动态路由
router.beforeEach((to, from, next) => {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
const accountStore = useAccountStore();
const token = accountStore.token
if (token) {
dbApi.getRouter({}).then((response) => {
const res = response.data
asyncRouter = res.data
asyncRouter.push({
component: "error/404",
name: "404",
path: "/:catchAll(.*)"
});
store.commit('setRouters', asyncRouter)
goTo(to, next,asyncRouter)
})
} else {
if (to.path === '/') {
next()
}
}
}
})
router.afterEach(() => {
//....
})
function goTo(to, next,asyncRouter) {
asyncRouter.forEach((route) => {
router.addRoute(route) //注意这里是vue3添加路由方式,与Vue2有所区别
})
next({...to, replace: true})
}