我有一个Vue组件,试图在其中使用axios从API提取一些数据。
db.sample.aggregate(
[
{
$addFields: {
totalList: { $size: "$List" } //This is for #1
}
},
{ $project : {
"Text":1,
"Title":1,
"totalList":1,
__v:{
$cond: {
if: { $eq: [1,1] }, //This is for #2
then: "$$REMOVE",
else: 0
}
},
List:
{
$reduce: //This is for #3
{
input: "$List",
initialValue: "",
in: {
$concat: [
"$$value",
{
$cond: {
if: { $eq: [ "$$value", "" ] }, //This is for #4
then: "",
else: ", "
}
},
"$$this"
]
}
}
}
}
},
{
$project : {
"Text" : 1,
"Title" : 1,
"__v" : 1,
"List" : { $substr: [ "$List", 0, 50 ] }, //This is for #5
"totalList":1
}
}
]
);
<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>
函数位于Vue组件文件之外的另一个JS文件中,该文件使用axios.get进行API调用。
getTools()
问题是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}}
需要一些时间来返回响应数据。如何等待响应数据然后返回?
答案 0 :(得分:2)
尝试以下代码:这样,代码仅在实际加载时才会呈现
<div v-if="tools">
This is Default child component
{{tools[0].name}}
</div>
答案 1 :(得分:1)
<template>
<div v-if="isGetTools">
This is Default child component
{{tools[0].name}}
</div>
</template>
<script>
import { CustomJS } from '../js/custom.js';
export default {
name: 'HomeContent',
props: {
tools: []
},
data: function () {
return {
isGetTools: false
}
},
methods: {
fetchData() {
const customJs = new CustomJS();
this.tools = customJs.getTools();
this.isGetTools = true;
}
},
created() {
this.fetchData(); //preferably need to wait here wait for response
}
}
</script>
尝试在div中添加v-if。从AXIOS获取结果后,将isGetTools更新为true
答案 2 :(得分:0)
您需要从请求中返回承诺
<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 new Promise((resolve, reject) => {
customJs.getTools()
.then(res => resolve(res))
.catch(err => reject(err))
})
}
},
created() {
this.fetchData().then(res => {
this.tools = res);
} //preferably need to wait here wait for response
}
}
</script>
答案 3 :(得分:0)
尝试获取已装载的数据
<template>
// try adding this condition on div element.
<div v-if="tools.length">
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();
}
},
mounted: function () {
this.tools = this.fetchData();
// or
// const customJs = new CustomJS();
// this.tools = customJs.getTools();
}
}
</script>
答案 4 :(得分:0)
您要做的是将getTools函数定义为如下所示的promise:
getTools (id = 0) {
return new Promise((resolve, reject) => {
this.apiTool += (id > 0) ? id : '';
axios.get(this.apiTool, {
})
.then(function (response) {
console.log(response.data);
resolve(response.data);
})
.catch(function (error) {
console.log(error);
reject(error)
});
})
}
然后您可以在组件代码中使用它,如下所示:
<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();
customJs.getTools().then((result) => {
return result;
}
)
}
},
created() {
this.tools = this.fetchData(); //preferably need to wait here wait for response
}
}
</script>
或使用异步/等待:
<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: {
async fetchData() {
const customJs = new CustomJS();
return await customJs.getTools()
}
},
created() {
this.tools = this.fetchData(); //preferably need to wait here wait for response
}
}
</script>
答案 5 :(得分:0)
通常,我正在使用加载程序向用户显示请求正在进行中
<div v-if="loading">
<loader /> //a loader component
</div>
<div v-else>
// show the template since request finished
</div>
和脚本
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
}
}
如果您不喜欢上述方式,则可以使用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()
})
}
}
答案 6 :(得分:0)
我不知道为什么这个问题会在我的“时间轴”中弹出,并且还没有被接受的答案,所以无论如何我都会回答。问题似乎在于对具有JS中异步代码的OP的理解。这是使它变得更好的解决方法(共有3种):
<template>
<div v-if="tools.length">
{{tools[0].name}}
</div>
<div v-else> // I. Use v-if/v-else to conditionally show data, in Vue 3 there will be another feature called "suspense" borned to do those things: https://vueschool.io/articles/vuejs-tutorials/suspense-new-feature-in-vue-3/
This is Default child component
</div>
</template>
<script>
import { CustomJS } from '../js/custom.js';
export default {
name: 'HomeContent',
props: {
tools: []
},
methods: {
async fetchData() {
const customJs = new CustomJS();
this.tools = await customJs.getTools();
// II. The OP assigned a promise to this.tools, this.tools wasn't being assigned to any actual data at all, because:
// 1. getTools() didn't return any data
// 2. even if it returned data, it wasn't being promise-resolved (by await/then) before assigned to this.tools
}
},
created() {
this.fetchData();
}
}
</script>
async getTools(id = 0){
this.apiTool += (id > 0) ? id : '';
try {
const response = await axios.get(this.apiTool, {});
console.log(response.data);
return response.data;
// III. The OP didn't return any fetched data at all, it just called API then do nothing. All the returns were returned in the arrow functions, the actual function getTools didn't get any return
}
catch (err) {
console.log(err)
}
},