Vue路由器this。$ router.push无法使用方法

Tha*_*tos 6 vue.js vue-router

我正在登录,但是登录方法成功后,我正在为该$router对象推路由,但该路由不起作用,有人可以帮助我吗?

我的代码:

doLogin(){
       this.attemptLogin({...this.user}).then(function(){
            this.$router.push('/') 
            } )
  },
Run Code Online (Sandbox Code Playgroud)

因此,登录方法按预期执行,但回调this.$router.push('/')未运行

attemptLogin是一个动作,它的代码如下:

export const attemptLogin = ( {commit}, user) => {
    return http.post('login', {
        'email': user.email,
        'password': user.password
    }).then(response => {
        return commit(types.setToken, response.data)
    }).catch( e => console.log(e))
}
Run Code Online (Sandbox Code Playgroud)

小智 12

就我而言,我发现我的beforeRouteUpdate不执行next()方法

坏的:

beforeRouteUpdate(to, from, next) {
  /*
  something...
  */
}
Run Code Online (Sandbox Code Playgroud)

好的:

beforeRouteUpdate(to, from, next) {
  /*
  something...
  */

  next() // DO IT!
}
Run Code Online (Sandbox Code Playgroud)

  • 天啊,谢谢!!我知道这个问题不是“导航卫士”会成为问题的地方。但这就是我的问题所在。 (3认同)

小智 10

您必须输入名称或路径,请尝试以下操作:

this.$router.push({ path: '/' })
this.$router.push({ name: 'Home' })
Run Code Online (Sandbox Code Playgroud)

  • 不,你不知道。router.push(位置,onComplete?,onAbort?) https://router.vuejs.org/guide/essentials/navigation.html#router-push-location-oncomplete-onabort (2认同)

Tha*_*tos 9

解决了,我将方法this.$router.push()从代码更改为this.$router.go('/')

感谢大家的评论。

  • 但是为什么要成功,我需要从文档中找出答案 (3认同)

小智 6

我也遇到了同样的问题, this.$router.push('/') 似乎不起作用,因为我没有重定向,日志中也没有错误。我没有意识到的是,我有一个小中间件正在寻找是否设置了身份验证令牌。我在错误的商店里找了它,所以自然它总是会摔倒。如果有中间件,请记住查看中间件,因为它不会在 router.push() 上返回错误


小智 5

我知道这个话题有点老了,但是在使用 Nuxt 和 Vue 时遇到了这个问题,我只想提供一些可能对某些人有所帮助的更新。

login() {
    this.$auth.loginWith('local', {
        data: {
            username: this.username,
            password: this.password,
        }
    });
    this.$router.push({name: 'dashboard'});
}
Run Code Online (Sandbox Code Playgroud)

我的代码最初是这样的,但我忘记确保我使用的是 Promise 或使用 Async / Await 方法。

正确的代码(就我而言)如下所示;

async login() {
    await this.$auth.loginWith('local', {
        data: {
            username: this.username,
            password: this.password,
        }
    });
    this.$router.push({name: 'dashboard'});
}
Run Code Online (Sandbox Code Playgroud)

正如我所说,.then()如果需要,您可以使用等。但我不想不把它放在那里给可能需要它的人。我的菜鸟错误。