在做項目的時候,可能需要在其他模塊獲取推送的信息或者變量,但是數據量或者說數目少,而且項目中也沒有引用VUEX,那么可以下手的方法之一也就是sessionStorage類的瀏覽器存儲了。
首先在全局的main.js中寫入:
// 全局獲取緩存數據 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); } },
設置/修改方法就簡單了:
Vue.prototype.resetSetItem('watchStorage', 'false'); (在API中引入,引入文件為:import Vue from 'vue' )
或:
this.resetSetItem('watchStorage','false');
在需要的地方進行監聽:
window.addEventListener('setItem', ()=> { _this.newVal = sessionStorage.getItem('watchStorage'); })
監聽方法可以寫在文件的create 或mounted中即可。