有没有办法在 VueJS 中缓存 API 响应

kal*_*i M 8 javascript caching node.js vuejs2

在我们的 VueJS 应用程序中,我们只有很少的 API,每次页面重新加载时都会调用这些 API。在那些 API 中。很少有回应永远不会改变,也很少有人很少改变。我计划缓存这些 API 调用响应并将其存储在一个变量中,并在需要时使用它,并减少页面重新加载时的请求数量。

我是 vueJS 的新手,不知道如何实现它。有没有办法在 VueJS 或 Javascript 中实现这一点?非常感激任何的帮助。

示例 HTML 代码,

<div class="col-sm-6">
    <span>Is User Available? {{userInfo[is_user_available]}}  </span>
    <span> User Type : {{userType}} </span>
</div>
Run Code Online (Sandbox Code Playgroud)

API 调用如下所示,

created: function () {
    this.checkForUser();
},
methods: {
    checkForUser: function() {
        this.api.call('user_info', { username : this.username })
        .then((response) => {
            if (response) {
                this.userInfo = response;
                this.userType = this.userInfo['user_type'];
            }
        })
        .catch((error) => {
            this.userInfo.length = 0;
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

Mys*_*ood 1

有几种方法可以做到这一点,具体取决于您想要深入的程度:

如果您只想在 SPA 会话期间保持状态,您可以这样做:

  • Vuex如果你想存储全局可访问的状态/数据。这允许您的状态持续存在,无论组件是否被销毁/创建。

  • 将其存储在根级 Vue 实例上。如果您使用的是 Vue CLI,则该文件将位于您的 main.js 中。你可以这样做:

new Vue({
  // ...
  data: {
    userType: {}
  }
})
Run Code Online (Sandbox Code Playgroud)

然后您可以通过 访问它this.$root.userType。这对于小型项目来说很好,但通常不推荐,因为事情很快就会变得混乱。

  • 还有EventBus,但同样,这很快就会变得混乱。EventBus 在 Vue3 中也已被弃用。

如果您想缓存响应并在用户关闭选项卡/浏览器后再次访问它们,您将需要研究:

  1. 饼干
  2. 本地存储
  3. 服务工作者