在根目錄下創建一個名為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++; } } }); },