Vue JS:单页应用程序中app.Vue上的API调用请求



在我的项目中,我遇到了API请求延迟的问题,这是因为我在API中有大量数据,所以我添加了缓存,但当页面创建时,它仍然显示为白色页面,所以我考虑在app.vue上添加API调用,这样请求会更快。。。有办法做到吗?现在,我正在我的项目中的每个页面上提出API请求以下代码:

//building.vue where buildings api used
<template>
<b-row class="icon-examples">


<b-col lg="3" md="6"  v-for="(building, index) in buildings"
:key="index" >

<button type="button" class="btn-icon-clipboard" @click="GoToBuilding(building._id)"
>
<div>
<i class="ni ni-building"></i>
<router-link
class="question-routerToDetail"
:to="`/tables/${building._id}`"
>      <span > B info - </span>
<span>{{building.building_number}}</span></router-link>
</div>
</button>
</b-col>

</b-row>
</template>
<script>
import BuildingsService from "../../../services/ApiService"
export default {
data() {
return {


};
},
components: {
props:
['buildings'],

BaseHeader,
//  buildings:[]
},

}
}
</script>

app.vue:

<template>

<router-view :number="count" @send="getNewCount"   @reset="onReset" :buildings="buildings">
<sidebar :number="count" @reset="onReset"/>
</router-view>
</template>
<script>
export default {
components: {
sidebar,
},
data() {
return {
buildings: []
};

},

created(){
BuildingsService.getBuildings().then((response) => {
this.buildings = response.data.response;
console.log(this.buildings , "skk")
});
}
}
</script>

我可以在app.vue中添加保存的API请求数组并在其他页面上使用它吗?它会改善我的API调用吗?

提前感谢

编辑:根据以下答案更新问题。。但是在没有控制台错误的情况下获得空数据

是的,您可以在包含router-view的组件中一次调用API,并通过道具将结果传递给渲染组件。呈现的组件必须声明将传递给它们的props,但前提是它们将使用它

<template>
<router-view :number="count" 
@send="getNewCount" @reset="onReset"
:buildings="buildings">
<sidebar :number="count" @reset="onReset"/>
</router-view>
</template>
<script>
import BuildingsService from "../../../services/ApiService"
export default {
components: {
sidebar,
},
data() {
return {
buildings: []
};
},
created(){ 
BuildingsService.getBuildings().then((response) => {
this.buildings = response.data.response;
});
}
}
</script>

但是,如果API调用返回大量数据或速度非常慢,那么我真的建议您检查优化API的后端查询,对结果进行分页,并通过滚动加载或其他方式逐渐加载结果。

此外,如果你能在你的状态下保留一些东西来检查数据是否正在加载,这样你就可以显示一个加载程序或其他东西,而不是一个白色页面,直到你得到结果。

一种可能的解决方案是调整getBuild((,这样它只调用后端一次,并将结果存储在BuildingsService的属性中,例如cachedBuildings

如果cachedBuildings为空,则getBuildings((调用后端并将结果存储在cachedBuilding中。

如果cachedBuildings不为空,getBuildings((将返回cachedBuilders。

此解决方案的优点是,您只需在一个位置调整代码,并且缓存对每个组件都是透明的。

最新更新