2017-04-16 53 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

我已經發布了代碼在這裏,它的工作原理,我不知道爲什麼,它記錄了正確的價值,但是當我嘗試使用它進行測試時,它似乎無法正常工作,請檢查我發佈的內容 –