1、需求:
一个页面数据变化要改变另一个页面,甚至整个项目的数据变化
2、在main.js中:
/**
* @description 监听本地储存的值变化
* @param { number } type 1 localStorage 2 sessionStorage
* @param { string } key 键
* @param { string } data 要存储的数据
* @returns
*/
Vue.prototype.$addStorageEvent = function (type, key, data) {
if (type === 1) {
// 创建一个StorageEvent事件
var newStorageEvent = document.createEvent('StorageEvent');
const storage = {
setItem: function (k, val) {
localStorage.setItem(k, val);
// 初始化创建的事件
newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
// 派发对象
window.dispatchEvent(newStorageEvent);
}
}
return storage.setItem(key, data);
} else {
// 创建一个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, data);
}
}
3、页面使用:
【页面A】
this.$addStorageEvent(1, 'deptId', JSON.stringify(This.formData.deptId));//存储数据,addStorageEvent自定义方法
//this.$addStorageEvent(2, 'deptId', JSON.stringify(This.formData.deptId));//存储数据,addStorageEvent自定义方法
【页面B】
mounted() {
const that = this
// 在mouted钩子函数中进行监听localStorage
window.addEventListener('setItem', () => {
that.formData.deptId = JSON.parse(localStorage.getItem('deptId'))
//that.formData.deptId是data里面声明的变量
//that.formData.deptId = JSON.parse(sessionStorage.getItem('deptId'))
})
},