在vue中實現監聽localstorage中某個鍵對應的值的變化


在根目錄下創建一個名為utils的文件夾,在文件夾中創建一個localstorage.js文件

export default function tools () {
  const signSetItem = localStorage.setItem;
  localStorage.setItem = function (key, val) {
    const setEvent = new Event('setItemEvent');
    setEvent.key = key;
    setEvent.value = val;
    window.dispatchEvent(setEvent);
    signSetItem.apply(this, arguments);
  };
}

 

在main.js中引入使用

import storage from './utils/locaStorage';
Vue.use(storage);

 

在需要監聽localstorage中數據變化的文件中加以下代碼

// 監控locaStorage
    watchStorage () {
      const that = this;
      window.addEventListener('setItemEvent', function (e) { // 監聽setitem的 key ,執行對應的業務邏輯
        console.log(e.key, e.value);
        if (e.key === 'isFullScreen') {
          if (e.value) {
            that.textAreaMix = 1;
            that.textAreaMax = 14;
            that.componentKey++;
          } else {
            that.textAreaMix = 1;
            that.textAreaMax = 1;
            that.componentKey++;
          }
        }
      });
    },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM