Reputation: 9859
I have got 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
retrieve content. But when I try to print it with: console.log(this.$get('questions'));
on Chrome Console I see only empty object. It's seems that it's not loaded at moment of printing it with console.log
. How can I fix it?
Upvotes: 1
Views: 96
Reputation: 25221
Your callback function is not running within the scope of your vue component. You need to bind this
to the function so that you can set this.questions
:
this.$http.get('http://127.0.0.1:8080/js/questions.json').then(function(response)
{
this.questions = response.data;
}.bind(this));
You won't have access to the questions until the callback function of the asynchronous request. So calling this.foo()
immediately after sending the request won't ever show data.
Upvotes: 1
Reputation: 895
Try with asynchronous function. Maybe something like that :
this.getQuestionsContent(function(questions) {
console.log(questions);
})
with
getQuestionsContent(callback) {
this.$http.get('http://127.0.0.1:8080/js/questions.json').then(function(response)
{
callback(response.data);
});
}
The callback function is called only when you get the response from the server.
Upvotes: 0