I have the following Vue.js component:
module.exports = {
data: function () {
return {
searchText: "",
searchResult: []
}
},
watch:
{
searchText: function() {
this.searchResult = this.search()
}
},
methods:
{
search: function()
{
var result = [];
var _self = this;
$.getJSON("data/data.json", function(json) {
$.each(json, function(index, obj) {
if (_self.searchText.length > 0 && obj.text.indexOf(_self.searchText) != -1)
result.push(obj);
}, this);
});
return result;
}
}
}
This code works well, but I don't understand why:
Why search() doesn't return an empty array without waiting for the result of $.getJSON() which is an asynchronous function? Surprisingly (for me), it only returns after the callback function is completed.
result.slice()which create a copy of the array, in this context it'll be your snapshot. Then you should see it's indeed empty :)