【发布时间】:2018-12-21 15:40:42
【问题描述】:
我有一个 Vue 组件,我正在尝试使用 axios 从 API 获取一些数据。
<template>
<div>
This is Default child component
{{tools[0].name}}
</div>
</template>
<script>
import { CustomJS } from '../js/custom.js';
export default {
name: 'HomeContent',
props: {
tools: []
},
methods: {
fetchData() {
const customJs = new CustomJS();
return customJs.getTools();
}
},
created() {
this.tools = this.fetchData(); //preferably need to wait here wait for response
}
}
</script>
getTools() 函数位于 Vue 组件文件之外的另一个 JS 文件中,它使用 axios.get 进行 API 调用。
getTools(id = 0){
this.apiTool += (id > 0) ? id : '';
axios.get(this.apiTool, {
})
.then(function (response) {
console.log(response.data);
return response.data;
})
.catch(function (error) {
console.log(error);
});
}
问题是,{{tools}} 未定义,因为getTools() 需要一些时间才能返回响应数据。怎样才能等待响应数据然后返回?
【问题讨论】:
-
如果要等待请求完成,可以在getTools()中使用同步http请求
-
@SagarTamang 不,不是一个好主意。
sync已弃用,请不要建议人们使用随时可能消失的功能。 -
什么是你需要等待,..你能不能做 ->
this.fetchData().then(......? -
@Keith 好的,我会记住的。非常感谢。
-
我在这里得到了部分解决方案-stackoverflow.com/questions/43613115/…
标签: javascript vue.js axios