在根目录下创建一个名为utils的文件夹,在文件夹中创建一个localstorage.js文件
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);
};
}
在main.js中引入使用
import storage from './utils/locaStorage';
Vue.use(storage);
在需要监听localstorage中数据变化的文件中加以下代码
// 监控locaStorage
watchStorage () {
const that = this;
window.addEventListener('setItemEvent', function (e) { // 监听setitem的 key ,执行对应的业务逻辑
console.log(e.key, e.value);
if (e.key === 'isFullScreen') {
if (e.value) {
that.textAreaMix = 1;
that.textAreaMax = 14;
that.componentKey++;
} else {
that.textAreaMix = 1;
that.textAreaMax = 1;
that.componentKey++;
}
}
});
},