在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');
})
相關文章
相關標籤/搜索