位置:首页 > web前端 > vue

Redirected when going from "/a?redirect=%2Fhome" to "/home" via a navigation guard.

dearweb 发布:2022-11-03 09:45:33阅读:

今天在使用vue开发项目时遇到了路由跳转保存的问题,Redirected when going from "/login?redirect=%2Fhome" to "/home" via a navigation guard,查阅了不少资料,最终找到了解决方案,先分享给有需要的小伙伴们。

image.png

官方文档所说

xt: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 - xt 方法的调用参数。


xt(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。


xt(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。


xt(’/’) 或者 next({ path: ‘/’ }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: ‘home’ 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。


xt(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

分析

很显然这并不是代码问题,很可能是官方bug

解决

方案1:将vue-router版本调整至3.0.7

更换vue-router版本为: npm i vue-router@3.0 -S

方案2:在 route.js 下补充以下代码

const originalPush = Router.prototype.push
Router.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject){
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

如果上面的方法不行,你还可以换种写法

// 获取push方法原型
const hackerTargets = ['push', 'replace'];
hackerTargets.forEach((target) => {
  const originalFunction = VueRouter.prototype[target];
  // 更改原型方法
  VueRouter.prototype[target] = function doingHack (location, onResolve, onReject) {
    // 劫持成功或者失败的函数,忽略掉异常报错
    if (onResolve || onReject) return originalFunction.call(this, location, onResolve, onReject);
    return originalFunction.call(this, location).catch(err => err);
  }
})

以上的方法,小编亲测,还是可以的。

24人点赞 返回栏目 提问 分享一波

小礼物走一波,支持作者

还没有人赞赏,支持一波吧

留言(问题紧急可添加微信 xxl18963067593) 评论仅代表网友个人 留言列表

暂无留言,快来抢沙发吧!

本刊热文
网友在读
手机扫码查看 手机扫码查看