main.js
// 自定义监听sessionStorage的方法
Vue.prototype.$addStorageEvent = function (type, key, data) {
if (type === 'setItem') { //type为setItem时执行下面的方法
// 创建一个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);
}
}
// 存值
this.$addStorageEvent(
"setItem",
"watchStorage",
JSON.stringify(this.isMoreExpand)
);
// 监听取值
window.addEventListener("setItem", () => { let skin = JSON.parse(sessionStorage.getItem("watchStorage")); }, 500);
这篇博客介绍了如何在Vue中自定义监听sessionStorage的setItem方法,通过创建并派发StorageEvent来实现监听。文章展示了如何存储值以及如何监听并获取存储的值,特别适合前端开发者了解和学习Vue中本地存储的定制化操作。
3759

被折叠的 条评论
为什么被折叠?



