vue-router4 路由错误 createRouterError

492 阅读1分钟

问题出现原因:由于权限原因没有把一些页面加入路由,此时进行[ this.$router.push ]就会发生中断性异常,

image.png

这个时候并没有经过路由守卫,所以没法在 [router.beforeEach] 里进行失败处理; 使用官方api配置的404跳转也不第生效

    { path: '/:pathMatch(.*)*', name: 'not-found', component: NotFound }, 
    { path: '/:pathMatch(.*)', name: 'bad-not-found', component: NotFound },

在网上遍寻无果,只能看异常内容:

image.png 可以看出 createRouterError 是由 this.$router.push({name:"xxx"}) 抛出, 只有使用 path 模式才不会直接抛出异常, 然后才得以正常跳转到 官方api配置的404, 然后经过 路由守卫 [router.beforeEach], 然后在守卫里进行处理, 如:

调用:

 this.$router.push({path: "/xxx" })

守卫处理:

  if(to.name === 'bad-not-found'){
    ElMessage.warning({title: '警告', message: '无权进行此操作,请联系管理员!'})
    return;
  }

具体原因因为时间关系,且本人纯属外行,所以暂不能解释不清楚!