【问题标题】:Can I cache an API call object using Vue JS lifecycle hooks?我可以使用 Vue JS 生命周期挂钩缓存 API 调用对象吗?
【发布时间】:2020-05-01 07:43:23
【问题描述】:
我正在使用 The Strain API,它有一个搜索查询,可以获取其数据库中的所有菌株。它说要谨慎使用它,因为它需要大量的计算能力。我的问题是:我可以在 App 组件生命周期挂钩中调用一次,将响应保存在 App data() 中,并以某种方式缓存它,这样如果 data.object.length != 0,它就不会尝试调用又来了?然后我可以将它作为道具传递给需要它的任何其他组件。抱歉,VueJs 和编程新手。
【问题讨论】:
标签:
vue.js
logic
lifecycle
【解决方案1】:
在我看来最好的办法是将计算出的数据保存在一个服务中,这样你就可以在你挂载的组件中简单地调用从 StrainService.js 导入的 getData()
// StrainService.js
let response = null;
const getData = async () => {
if (!response) {
response = await StrainApiCall()
}
return response
}
const StrainApiCall = () => {
return axios.get('yourdata.com') // your api call
}
export {
getData
}