Sou*_*osh 6 javascript vue.js axios
我有一个 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>
Run Code Online (Sandbox Code Playgroud)
该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);
});
}
Run Code Online (Sandbox Code Playgroud)
问题是,{{tools}}未定义,因为getTools()返回响应数据需要一些时间。如何等待响应数据然后返回?
试试下面的代码:这样代码只会在它实际加载时呈现
<div v-if="tools">
This is Default child component
{{tools[0].name}}
</div>
Run Code Online (Sandbox Code Playgroud)
通常,我使用加载程序向用户显示请求正在进行中
<div v-if="loading">
<loader /> //a loader component
</div>
<div v-else>
// show the template since request finished
</div>
Run Code Online (Sandbox Code Playgroud)
和脚本
export default {
data: () => ({
loading: false
}),
created() {
this.loading = true
axios.get('api') //your request
.then(response => console.log(response))
.finally(() => (this.loading = false)) //when the requests finish
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不喜欢上面的方式,您可以使用beforeEnter这样的方式,只有当请求完成时才会加载路由:
{
path: '/my-route',
component: YourComponent,
props: true,
beforeEnter (to, from, next) {
axios.get('api-request')
.then(response => {
to.params.data = response //we pass data through props to the component
next()
})
}
}
Run Code Online (Sandbox Code Playgroud)