【问题标题】:Vue. How to watch localstorage for changes?Vue。如何查看本地存储的变化?
【发布时间】:2019-10-12 11:45:51
【问题描述】:

另一个脚本(没有 vue.js)在本地存储中写入一些数据,例如数组“链接”。但是我的 vue 应用程序只有在页面重新加载后才能看到它(因为 localstorage 在 vue 中没有反应)。如何在不重新加载页面的情况下查看 localstorage 的更改和显示?

【问题讨论】:

  • @StevenSpungin 不,这是另一种情况
  • "(因为 localstorage 在 vue 中没有反应)" localStorage 没有反应。不仅在 Vue 中????我看到的唯一可能性是订阅状态或 vuex 中的操作。然后在每次尝试做某事时检查 localStorage。
  • 虽然这不是您要问的,但如果可能的话,我建议您重新考虑您的应用程序架构,因为即使轮询会起作用,它也是必不可少的,而且在性能方面并不是最好的。由于您还没有公开您的代码,因此很难提出具体的建议,但是如果您还没有的话,不妨看看 vuex!

标签: vue.js


【解决方案1】:

本地存储并不是真正为不断更新的动态数据而设计的,但假设您无法控制它。

VueJS 只监视其组件中的数据,因此您不能使用 VueJS。

一个不太好的解决方案是使用 setInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval),它每 x 秒运行一次并从 localStorage 获取值。

它既不漂亮也不高效,就像

let name = 'Bergur'
setInterval(function() {
name = localStorage.getItem('name')
}, 5000)

【讨论】:

    【解决方案2】:

    如果您想查看不受您影响的本地存储更改,可以对其进行轮询。

    data() {
        return {
          lastChange: null,
          timer: null
        }
      },
      created() {
        let curVal = localStorage.getItem('foo');
        this.lastChange = new Date()
        this.timer = setInterval(() => {
          const newVal = localStorage.getItem('foo');
          if (newVal !== curVal) {
            curVal = newVal;
            // fireEvent, update state, etc
            // or update data in your component
            this.lastChange = new Date()
          }
        }, 1000);
      },
      beforeDestroy() {
        cleaInterval(this.timer)
      }

    【讨论】:

      猜你喜欢
      • 2019-06-20
      • 2021-06-01
      • 1970-01-01
      • 2011-08-30
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多