redirect after axios response with vue

2020-06-27 05:49发布

Ok, so i have the following method. Basically I am calling an API backend, posting username and password, and if those pass, in the response, the server sends me a 200 status. What I want to do, is in the response, after I get the status, run an if/else, so if the status is 200, redirect, else display an error message. every time i try to use 'this.$router.push('/any route here')',

I get an error: 'homepage.vue?3ec6:72 Uncaught (in promise) TypeError: Cannot read property '$router' of undefined'.

But if i use the same route at the top of the method, outside the axios call, it works fine.

So what am i missing here?

                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);
                     })
                   }

4条回答
Deceive 欺骗
2楼-- · 2020-06-27 06:19

Use route name

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

Use route URL

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

Such as Vue Router Documentation

查看更多
Evening l夕情丶
3楼-- · 2020-06-27 06:21

please use this.$router.push('/home')

查看更多
Deceive 欺骗
4楼-- · 2020-06-27 06:30

You can use easily redirect it by using,

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

OR,

.then(data => {  
'this.$router.push({ name: "home" });
    });
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-06-27 06:36

You have to define this outside axios methods because this inside axios refers to the axios object, not the vue component:

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');
      }
    })
  }
}
查看更多
登录 后发表回答