在vue中监听storage的变化

一、首先在main.js中给Vue.protorype注册一个全局方法,其中,咱们约定好了想要监听的sessionStorage的key值为’watchStorage’,而后建立一个StorageEvent方法,当我在执行sessionStorage.setItem(k, val)这句话的时候,初始化事件,并派发事件。
session

Vue.prototype.resetSetItem = function (key, newVal) {
   if (key === 'watchStorage') {

       // 建立一个StorageEvent事件
       var newStorageEvent = document.createEvent('StorageEvent');
       const storage = {
           setItem: function (k, val) {
               sessionStorage.setItem(k, val);

               // 初始化建立的事件
               newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);

               // 派发对象
               window.dispatchEvent(newStorageEvent)
           }
       }
       return storage.setItem(key, newVal);
   }
}

二、如何触发
在一个路由(好比路由A)存储值得时候,使用下面的方法:函数

this.resetSetItem('watchStorage', this.value);

三、如何监听
若是在另一个路由(好比路由B)中,咱们想根据watchStorage的变化来请求接口刷新页面数据的时候,能够在这个路由中created钩子函数中监听:this

window.addEventListener('setItem', ()=> {
    this.newVal = sessionStorage.getItem('watchStorage');
})
相关文章
相关标签/搜索