我可以使用Vue JS生命周期挂钩来缓存API调用对象吗?

问题描述 投票:0回答:1

我正在使用The Strain API,该API的搜索查询可获取其数据库中的所有菌株。它说要谨慎使用它,因为它需要大量的计算能力。我的问题是:我可以在App组件生命周期挂钩中调用一次,将响应保存在App data()中,然后以某种方式缓存它,以便如果data.object.length!= 0时,它不会尝试调用再来一次吗?然后,我可以将它作为道具传递给需要它的任何其他组件。对不起,VueJ和编程的新手。

vue.js logic lifecycle
1个回答
0
投票

我认为最好的办法是将计算出的数据保留在服务中,这样您就可以在装入的组件中简单地调用从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
}
© www.soinside.com 2019 - 2024. All rights reserved.