I read all answered questions on stack overflow but still unable to figure out how to make this work.
File1.js
I send some data to server using axios ajax call as follows:
function ajaxSearchAxios(searchType,searchText){
var searchResults=[];
axios({
method: 'post',
url: 'ajaxSearch/',
data: {
searchType: searchType,
searchText: searchText,
},
responseType: 'json',
})
.then ( function (response){
searchResults = response.data['searchResults']; console.log('JS searchResults=',searchResults[0].value) //this prints nicely to the console
return searchResults
})
.catch ( function (error){
console.log('ajaxSearch error');
});
}
File2.js
Here I have my Vue code where I want to take output of ajaxSearchAxios()
and store in Vue data.
new Vue({
el:'#id_1',
data:{
SearchResults:[],
},
methods:{
ajaxSearch:function(searchType){
this.SearchResults= ajaxSearchAxios('s','s1');
console.log('VUE =',this.SearchResults[0].value)
},
},
});
Thanks
Remember, you're dealing with asynchronous functions, so your function needs to return and handle the functionality as a Promise
function ajaxSearchAxios(searchType,searchText){
return axios({ // <--- return the PROMISE
method: 'post',
url: 'ajaxSearch/',
data: {
searchType: searchType,
searchText: searchText,
},
responseType: 'json',
})
.then ( function (response){
return response.data['searchResults'];
})
.catch ( function (error){
console.log('ajaxSearch error');
});
}
and then handle it as a promise, instead of assigning the function to value
new Vue({
el:'#id_1',
data:{
SearchResults:[],
},
methods:{
ajaxSearch:(searchType) => {
// execute axios promise and on success, assign result to var
ajaxSearchAxios('s','s1').then(result => this.SearchResults = result)
},
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With