1.新建一个localstorage.js 代码中写上
//重写setItem事件,当使用setItem的时候,触发,window.dispatchEvent派发事件
export default function tools () {
const signSetItem = localStorage.setItem;
localStorage.setItem = function (key, val) {
const setEvent = new Event('setItemEvent');
setEvent.key = key;
setEvent.value = val;
window.dispatchEvent(setEvent);
signSetItem.apply(this, arguments);
};
}
2.在main.js中引用js文件
import storage from "@/api/common/localstorage";
Vue.use(storage);
3.在需要用的地方进行监听,我是在mounted中进行监听的
mounted() {
let _this = this;
window.addEventListener("setItemEvent", (e) => {
// e.key是存储的名字
if (e.key == "orgCode") {
_this.getQuerySysInfo(e.value);
}
});
}