1.在main.js 文件内进行全局注册,注意引入:
import Vue from 'vue'
Vue.prototype.resetSetItem = function (key, newVal) {
//KJQJ监听的session字段
if (key === 'KJQJ') {
// 创建一个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);
}
}
2.在要监听的页面created 或 mounted 方法内写入监听
window.addEventListener('setItem', () => {
alert('此处发生变化')
})
3.如何改变session的值
this.resetSetItem('KJQJ', '11111')