2016-02-25 29 views
1

我有Vue.extend:如何在加載後才能訪問數據?

data: function() { 
    return { 
    questions: [] 
    } 

    }, 
    ready() 
    { 
    this.getQuestionsContent(), 
    this.foo() 
    }, 
    methods: 
    { 

    getQuestionsContent() 
    { 
     this.$http.get('http://127.0.0.1:8080/js/questions.json').then(function(response) 
     { 
      this.questions = response.data; 

     }); 

     }, 
     foo() 
     { 
     console.log(this.$get('questions')); 
     } 

    } 

getQuestionsContent檢索內容。但是,當我嘗試在Chrome控制檯上使用:console.log(this.$get('questions'));進行打印時,我只看到空的對象。看起來它在console.log打印時沒有加載。我該如何解決它?

回答

1

您的回調函數未在您的vue組件的範圍內運行。您需要綁定this的功能,讓你可以設置this.questions

this.$http.get('http://127.0.0.1:8080/js/questions.json').then(function(response) 
    { 
     this.questions = response.data; 

    }.bind(this)); 

您將無法訪問的問題,直到異步請求的回調函數。因此,在發送請求後立即調用this.foo()將不會顯示數據。

0

嘗試使用異步功能。也許這樣的事情:

this.getQuestionsContent(function(questions) { 
    console.log(questions); 
}) 

getQuestionsContent(callback) { 
    this.$http.get('http://127.0.0.1:8080/js/questions.json').then(function(response) 
    { 
     callback(response.data); 
    }); 
} 

只有當你從服務器的響應回調函數被調用。

+0

我可以使用'activate Hook'嗎? –

相關問題