在 Vue.js 中等待 Ajax 响应数据 [英] Wait for Ajax response data in Vue.js
问题描述
我有一个 Vue 组件,我正在尝试使用 axios 从 API 获取一些数据.
<div>这是默认子组件{{工具[0].name}}
模板><脚本>从'../js/custom.js'导入{CustomJS};导出默认{name: 'HomeContent',道具: {工具: []},方法: {取数据(){const customJs = new CustomJS();返回 customJs.getTools();}},创建(){this.tools = this.fetchData();//最好需要在这里等待等待响应}}
getTools()
函数位于 Vue 组件文件之外的不同 JS 文件中,该文件使用 axios.get 进行 API 调用.
getTools(id = 0){this.apiTool += (id > 0) ?ID : '';axios.get(this.apiTool, {}).then(功能(响应){控制台日志(响应数据);返回 response.data;}).catch(函数(错误){控制台日志(错误);});}
问题是,{{tools}}
未定义,因为 getTools()
需要一些时间来返回响应数据.如何等待响应数据然后返回?
试试下面的代码:这样代码只会在实际加载时呈现
这是默认子组件{{工具[0].name}}
I have a Vue component where I am trying to fetch some data from an API using axios.
<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>
The getTools()
function is in a different JS file outside the Vue component file which makes the API call using axios.get.
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);
});
}
The problem is, {{tools}}
is undefined since the getTools()
takes some time to return the response data. How can wait for the response data and then return?
Try the code below: so the code will render only when its actually loaded
<div v-if="tools">
This is Default child component
{{tools[0].name}}
</div>
这篇关于在 Vue.js 中等待 Ajax 响应数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!