2017-04-16 51 views
1

发送一个请求并获得基于它的响应,我想挑战状态并显示一些不同的东西,找不出什么问题,路由似乎工作正常和我收到它看起来像这样enter image description here在laravel接收一个带有vue.js2的json响应

我试图访问该使用Vue的成分,我越来越没有定义的错误状态的响应,这是我的Vue组件

<script> 
    export default { 
     mounted() { 
       axios.get('/userfound/' + this.profile_user_id) 
       .then(function (response) { 
        console.log(response); 
        this.status = response.data.status;     
       }) 
       .catch(function (error) { 
        console.log(error); 
        }); 
       }, 
     props: ['profile_user_id'], 
     data(){ 
      return { 
       status: '' 
      }   
     }, 
     methods:{ 
      add_friend(){ 
       // this.loading = false 
       axios.get('/add_friend/' + this.profile_user_id) 
       .then(function (response) { 
        console.log(response); 
        if (response.data == 1) { 
         this.status = 'waiting' 
        } 

       }) 
       .catch(function (error) { 
        console.log(error); 
        }); 
       } 
      } 
     } 
</script> 

为什么我得到这个错误:TypeError: cannot read property 'status' of undefined .. 我试过"this.status = response.body.status""this.status = response.data.status"但都没有工作

回答

2

我相信有一个变量的范围问题。尝试下面的回答:

<script> 
export default { 
    mounted() { 
      var self = this; 
      axios.get('/userfound/' + self.profile_user_id) 
      .then(function (response) { 
       console.log(response); 
       self.status = response.data.status;     
      }) 
      .catch(function (error) { 
       console.log(error); 
       }); 
      }, 
    props: ['profile_user_id'], 
    data(){ 
     return { 
      status: '' 
     }   
    }, 
    methods:{ 
     add_friend(){ 
      // you can do same here as well 
      var self = this; 
      axios.get('/add_friend/' + self.profile_user_id) 
      .then(function (response) { 
       console.log(response); 
       if (response.data == 1) { 
        self.status = 'waiting' 
       } 
      }) 
      .catch(function (error) { 
       console.log(error); 
       }); 
      } 
     } 
    } 
</script> 
+0

它在im当前页面中工作,但当我刷新它会提出相同的错误 –

+0

这很奇怪。尝试使用chrome devtools进行调试。 – Pradeepb

+0

我已经发布了代码在这里,它的工作原理,我不知道为什么,它记录了正确的价值,但是当我尝试使用它进行测试时,它似乎无法正常工作,请检查我发布的内容 –