Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue切换路由控制台报错,Uncaught (in promise) #7

Open
hsingyin opened this issue Mar 24, 2020 · 0 comments
Open

vue切换路由控制台报错,Uncaught (in promise) #7

hsingyin opened this issue Mar 24, 2020 · 0 comments
Labels
bug Something isn't working vue vue.js

Comments

@hsingyin
Copy link
Owner

背景

升级了vue-router v3.1.6,加了路由守卫,判断没有携带token就指向登录页,强迫症患者看着控制台打出了一堆Uncaught (in promise) undefined十分难受。

原因

在vue-router v3.0.7之后push和replace返回的是promise不是回调,如果遇到路由守卫的next指定到某个页面(例如登录页面),需要主动catch这个promisereject。[issue2881] (vuejs/vue-router#2881 (comment)) 里posva给出了比较详细的回答和解决方案。

处理方案

  1. 每次push都去主动写一个空的回调(或者显式指定onComplete和onAbort回调函数)。
      this.$router.push({
        name: `${name}`
      }, () => {})

      // or
      this.$router.push({
        name: `${name}`
      },
      onComplete => {
        console.log('完成')
      },
      onAbort => {
        console.log('哦打断了')
      })
  1. 在引入router之前重写push方法。
const originalPush = VueRouter.prototype.push

VueRouter.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)
}
@hsingyin hsingyin added bug Something isn't working vue vue.js labels Mar 24, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working vue vue.js
Projects
None yet
Development

No branches or pull requests

1 participant