1.在main.js中添加全局获取缓存数据
Vue.prototype.resetSetItem = function (key, newVal) {
if (key === 'menuItem') {
// 创建一个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.存
this.resetSetItem("menuItem", JSON.stringify(keyPath));
3.监听
mounted() {
let _this = this;
window.addEventListener("setItem", _this.printLog());
},
methods: {
printLog() {
console.log("监听到数据变化");
this.role = sessionStorage.getItem("categoryId");
},
}