网络编程 发布日期:2025/10/28 浏览次数:1
出现这个问题的起因:在一个VUE页面中,引入两个组件,A组件实现基础信息展示,B组件展示列表,我要通过A组件的一个按钮触发状态,然后B组件根据A组件触发的状态来做业务处理,首先想到的是把状态放在localStorage,接下去就是在B组件怎么监听A组件状态
/**
* @description
* @author (Set the text for this tag by adding docthis.authorName to your settings file.)
* @date 2019-05-29
* @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);
}
}
还有一个简单封装监听localStorage
this.$addStorageEvent(2, "user_info", data);
或者
this.resetSetItem('watchStorage', jsonObj);
window.addEventListener('setItem', (e) => {
console.log(e);
});
或者
window.addEventListener('setItem', ()=> {
this.newVal = sessionStorage.getItem('watchStorage');
var data=JSON.parse(this.newVal)
console.log(data)
})
以上就是vue 项目如何监听localStorage或sessionStorage的变化的详细内容,更多关于vue 项目监听localStorage或sessionStorage的资料请关注其它相关文章!