【问题标题】:redirect after axios response with vue使用 vue 在 axios 响应后重定向
【发布时间】:2018-02-12 13:09:37
【问题描述】:

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

我收到一个错误:'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);
                     })
                   }

【问题讨论】:

    标签: vuejs2 axios vue-router


    【解决方案1】:

    你必须在 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');
          }
        })
      }
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        使用路线名称

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

        使用路由网址

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

        Vue Router Documentation

        【讨论】:

          【解决方案4】:

          你可以通过使用轻松重定向它,

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

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

          【讨论】:

            猜你喜欢
            • 2020-07-18
            • 2018-10-10
            • 2021-11-14
            • 2020-12-13
            • 2021-08-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多