導語:
在多個組件需要共用一個值的時候,應用父子組件傳值的知識會很麻煩,又沒有必要通過vuex來儲存幾個數據,剛好我本次項目的數據和session中數據的性質一致,因此把兩個數據存到了session中並實時監聽。(也可以多個)
1、將想要實時監聽的數據存儲到session中
‘username’為獲取共享數據的key值,_this.loginForm.name為存入的數據。
2、在main.js文件中編寫以下代碼:
Vue.prototype.resetSetItem = function (key, newVal) { // 創建一個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) } } // 根據判斷獲取session中存入的多個值 if (key === 'username') { return storage.setItem(key, newVal); } else if (key === 'value') { return storage.setItem(key, newVal) } }
3、在生命周期created中實現實時監聽
created() { window.addEventListener('setItem', ()=> { console.log(sessionStorage.getItem('username')) } } },