我阅读了有关堆栈溢出的所有已回答问题,但仍然无法弄清楚如何进行这项工作。
文件1.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');
});
}
Run Code Online (Sandbox Code Playgroud)
文件2.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)
},
},
});
Run Code Online (Sandbox Code Playgroud)
谢谢
请记住,您正在处理异步函数,因此您的函数需要返回并处理该功能作为 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');
});
}
Run Code Online (Sandbox Code Playgroud)
然后把它当作一个promise来处理,而不是把函数赋值给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)
},
},
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10672 次 |
| 最近记录: |