You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue Router中this.$router.push在methods内无法跳转求助

登录后路由跳转失效的问题解决

Hey,我一眼就发现问题所在了——你回调函数里的this上下文不对,导致没法访问Vue组件实例上的$router对象,所以跳转操作没执行起来。

先看你这段doLogin的代码:

doLogin(){ 
  this.attemptLogin({...this.user}).then(function(){ 
    this.$router.push('/') 
  } ) 
},

这里的then用了普通的function()作为回调,这种函数里的this会绑定到全局对象(浏览器里就是window),而不是你的Vue组件实例,所以this.$router其实是undefined,自然不会有跳转动作。

给你三种解决办法,选哪种都可以:

  1. 用箭头函数(最推荐,写法最简洁)
    箭头函数不会创建自己的this,会继承外层的this上下文(也就是你的Vue组件实例),这样就能正常调用$router.push了:
doLogin(){ 
  this.attemptLogin({...this.user}).then(() => { 
    this.$router.push('/') 
  } ) 
},
  1. 提前把this存到变量里
    在调用attemptLogin之前,把组件实例的this存成一个变量(比如that),然后在回调里用这个变量访问$router:
doLogin(){ 
  const that = this;
  this.attemptLogin({...this.user}).then(function(){ 
    that.$router.push('/') 
  } ) 
},
  1. 用.bind(this)绑定上下文
    给回调函数手动绑定组件实例的this,强制让它的上下文指向Vue实例:
doLogin(){ 
  this.attemptLogin({...this.user}).then(function(){ 
    this.$router.push('/') 
  }.bind(this)) 
},

额外要确认的点

另外看了你的attemptLogin action代码,它已经正确返回了Promise链(http.post返回Promise,你也return了整个请求链),所以只要登录请求成功,then回调就会被触发。如果还是有问题,可以检查一下浏览器控制台有没有错误日志,确认登录请求确实是成功的,没有走到catch分支里。

内容的提问来源于stack exchange,提问作者thau0x01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:46:55