关于监听localStorage变化的问题

vue项目,比如我在index.vue页面,点击一个按钮,然后用window.open新窗口打开一个页面(case.vue)

index.vue

const { href } = that.$router.resolve({
  name: 'case',
  query: {
     abc: 'abc'
  }
})
window.open(href, '_blank')

有如下代码

伪代码:

case.vue

public mounted() {
    window.localStorage.setItem('reportParams', JSON.stringify({}))
    window.localStorage.setItem('reportParamsObj', JSON.stringify({}))

    this.$nextTick(() => {
      window.addEventListener('storage', this.reportParamsObjStorage, false)
    })
  }
public destroyed() {
    window.removeEventListener('storage', this.reportParamsObjStorage)
  }
public reportParamsObjStorage(e: any) {
    // 一堆逻辑省略
    
    // 重点是这一句 ie11下就会导致页面卡死 内存溢出 不明白为什么
    window.localStorage.setItem('reportParamsObj', JSON.stringify({}))
    
    // 这两句都正常
    // localStorage.setItem('reportParamsObj', '')
    // localStorage.removeItem('reportParamsObj')
    }
  }

case.vue页面我打开一个还算正常,当我再打开一个case.vue页面就直接内存飙升,卡死了。
问题是解决了,但是不知道为啥,求各路大神解释下

阅读 8.7k
1 个回答

你这是个死循环,你监听了storage事件,然后在事件回调里面修改storage,然后又会触发storage事件,然后又修改storage......'

另外关键是

The StorageEvent is fired whenever a change is made to the Storage object.
This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made。

这就是为什么开多个页面会卡死的原因

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题