how can i return data from this.$http.get in vue js
Solution 1
If you just want to assign the returned results to a variable then try this:
ready: function() {
this.getCounties;
},
data: {
counties: []
},
methods:{
getCounties: function(val){
// ajax get County list
this.$http.get('/api/counties/' + val )
.success(function(counties){
this.counties = counties;
})
.error(function(){
}); //ajaxcall
} // displayCounty
}
Solution 2
I think you are misunderstanding the asynchronous nature of $http.get
. The return you have of return counties
is not going to effect the return value of displayCounty
. displayCounty
returns null
immediately and the return counties
later ends up doing nothing.
A good strategy to use in this case is to have the success
callback set counties
on the View Model. Then you can setup a watcher on counties
and process the data whenever it changes.
Related videos on Youtube
user3814670
Updated on June 11, 2022Comments
-
user3814670 almost 2 years
Hi I'm having problem in returning a data in my ajax call using vue js in laravel 5. I have an array of state and call the function of ajax inside the loop. The problem now is it seems that the ajax cannot returned a value. here's my code:
ready: function() { var dData = {}; for (var i=0; i<this.pState.selectedState.length; i++){ dData = this.displayCounty(this.pState.selectedState[i]) } console.log(dData); }, methods:{ displayCounty: function(val){ var nData = {}; // ajax get County list this.$http.get('/api/counties/' + val ) .success(function(counties){ return counties; }) .error(function(){ }) //ajaxcall }// displaCounty }
any idea guys?
-
user3814670 over 8 yearsWhat I did is assign this to a new variable like "var self = this" then in ajax i just assign the countries to self.countries and I can now get the values.
-
Set Kyar Wa Lar over 8 yearsHow about, if I don't want to assign that result to countries data?