创立实例:
//main.js 创立实例
Vue.prototype.$addStorageValue = function(key,data,type=true){
if(type){
console.log('创立一个StorageEvent事件');
//创立一个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{
// 此处能够创立一个雷同的sessionStorage的实例
console.log('创立一个StorageEvent事件');
//创立一个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);
}
}
调用:
//store.index.js
//this._vm.$addStorageValue('key',data,type)
this._vm.$addStorageValue('personData',JSON.stringify(state.personData),true)
监听:
mounted() {
window.addEventListener("setItem", e => {
if (e.key === "personData") {
let val = JSON.parse(e.newValue);
console.log(val);
}
});
实现
本文链接来源于
发表回复