美文网首页js css html
路由添加next({ ...to, replace: true

路由添加next({ ...to, replace: true

作者: 子绎 | 来源:发表于2022-05-09 15:52 被阅读0次

在使用 router.addRoutes动态添加路由后,需要手动添加next({ ...to, replace: true })进行重定向重新加载才可以识别到新添加的路由。
但是由于next({ ...to, replace: true })中的to解构,会导致当前路由和前一个路由不一致,vue会抛出重定向的错误。

解决方案:
在router/index.js中添加如下代码 (推荐)

const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error)
}
Vue.use(Router)

第二种解决方案(不推荐,但也有用)
在要跳转之前 添加.catch监听,只需要监听vue即将抛出的路由异常,vue就不会主动在控制再抛红色错误

this.$router.push('/').catch(()=>{})

相关文章

网友评论

    本文标题:路由添加next({ ...to, replace: true

    本文链接:https://www.haomeiwen.com/subject/aeilurtx.html