2017-08-16 32 views
0

我正在使用vue2,並且正在嘗試獲取api並在我的頁面中呈現內容,這些都是在我的Orgs.vue文件中完成的,這裏是代碼:屬性或方法「orgs」未在實例上定義,但引用爲

<template lang="html"> 
    <div class=""> 
    {{ orgs | json }} 
    </div> 
</template> 

<script> 
export default { 
    data: { 
    orgs: false 
    }, 

    created() { 
    request = axios({ 
     url: 'https://....', 
     method: 'GET', 
    }) 
     .then(function(response) { 
     this.orgs = response; 
     }) 
     .catch(function(error) { 
     console.log('error getting orgs::', error); 
     }); 
    } 
}; 
</script> 

<style lang="css"> 
</style> 

但是每次我運行該頁面我得到這個錯誤:

Property or method "orgs" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. found in Orgs.vue

我試圖改變

data: { 
    orgs: false 
    }, 

data() { 
    return {orgs: false} 
    }, 

,但依然出現

+0

您是否嘗試過'data:function(){return {orgs:false}}',如https://vuejs.org/v2/guide/single-file-components.html中的示例 – harrypujols

+2

可能重複[如何在回調中訪問正確的\'this'?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Bert

回答

1

你需要做的請求之前保存可變VUE實例引用和響應處理程序使用它來訪問VUE。在例子中我使用了vue_instance
和組件init data作爲函數。

data: function() { 
    return { 
     orgs: false 
    } 
    }, 

    created() { 
    var vue_instance = this; 
    request = axios({ 
     url: 'https://....', 
     method: 'GET', 
    }) 
     .then(function(response) { 
     vue_instance.orgs = response.data; 
     }) 
     .catch(function(error) { 
     console.log('error getting orgs::', error); 
     }); 
    } 

編輯:在Axios公司響應處理器thiswindow參考。 Axios對vue一無所知。

+0

但爲什麼不能't'這個'在axios裏面工作? – hidar

+0

@hidar檢查我的編輯。 –

相關問題