在使用 vue 进行 axios 响应后重定向

redirect after axios response with vue

好的,所以我有以下方法。基本上我调用 API 后端,发布用户名和密码,如果通过,在响应中,服务器向我发送 200 状态。我想做的是在响应中,在我获得状态 运行 和 if/else 之后,如果状态为 200,则重定向,否则显示错误消息。每次我尝试使用 'this.$router.push('/这里的任何路线')',

我得到一个错误:'homepage.vue?3ec6:72 Uncaught (in promise) TypeError: Cannot read property '$router' of undefined'。

但是如果我在方法的顶部使用相同的路由,在 axios 调用之外,它工作正常。

那么我在这里错过了什么?

                hero_login: function(event){
                  event.preventDefault();

                  axios.post('API call here', 
                    { 
                      service:'client',
                      user: this.user_email,
                      password: this.user_password,
                      json:true
                    })
                    .then(function(response){
                       const status = 
                         JSON.parse(response.data.response.status);
                         console.log(status);
                     })
                   }

您必须在 axios 方法之外定义 this 因为 axios 内部的 this 指的是 axios 对象,而不是 vue 组件:

hero_login: function(event) {
  let self = this;

  event.preventDefault();

  axios.post('API call here', 
    { 
      service:'client',
      user: this.user_email,
      password: this.user_password,
      json:true
    })
    .then(function(response){
      const status = 
        JSON.parse(response.data.response.status);

      //redirect logic
      if (status == '200') {
       self.$router.push('/any route here');
      }
    })
  }
}

您可以使用

轻松重定向它
.then(data => {  
'this.$router.replace({ name: "home" });
    });

,

.then(data => {  
'this.$router.push({ name: "home" });
    });

请使用this.$router.push('/home')

使用路线名称

this.$router.push({name: 'home'});
this.$router.replace({name: 'home'});

使用路线URL

this.$router.push('/home');
this.$router.replace('/home');

比如Vue Router Documentation