我阅读了所有有关堆栈溢出的已回答问题,但仍然无法弄清楚如何使它工作。
File1.js
我使用axios ajax调用向服务器发送一些数据,如下所示:
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
这里有我的Vue代码,我想在其中获取ajaxSearchAxios()
的输出并存储在Vue数据中。
new Vue({
el:'#id_1',
data:{
SearchResults:[],
},
methods:{
ajaxSearch:function(searchType){
this.SearchResults= ajaxSearchAxios('s','s1');
console.log('VUE =',this.SearchResults[0].value)
},
},
});
谢谢
答案 0 :(得分:1)
我认为调用ajaxSearchAxios
正常,并且您已正确导入file1。如果是这样,Axios将返回一个Promise,因此请尝试返回axios obj并在Vue中使用async
和await
来等待类似这样的结果...
function ajaxSearchAxios(searchType,searchText){
var searchResults=[];
return axios({
method: 'post',
...
new Vue({
el:'#id_1',
data:{
SearchResults:[],
},
methods:{
ajaxSearch: async searchType => {
this.SearchResults = await ajaxSearchAxios('s','s1');
console.log('VUE =',this.SearchResults[0].value)
},
},
});
答案 1 :(得分:1)
请记住,您正在处理异步函数,因此您的函数需要以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');
});
}
然后将其作为一个承诺处理,而不是将函数分配给值
new Vue({
el:'#id_1',
data:{
SearchResults:[],
},
methods:{
ajaxSearch:function(searchType){
// execute axios promise and on success, assign result to var
ajaxSearchAxios('s','s1').then(result => this.SearchResults = result)
},
},
});
答案 2 :(得分:0)
Vue中来自axios的异步呼叫:
COPY