问题重点:重写localStorage.setItem事件
当使用setItem的时候触发 window.dispatchEvent派发事件
第一步
在根目录下创建utils文件夹,再创建一个tool.js文件
写下重写localStorage.setItem事件的代码
function dispatchEventStroage() {
const signSetItem = localStorage.setItem
localStorage.setItem = function(key, val) {
let setEvent = new Event('setItemEvent')
setEvent.key = key
setEvent.newValue = val
window.dispatchEvent(setEvent)
signSetItem.apply(this, arguments)
}
}
export default dispatchEventStroage;
第二步
在main.js全局引用该文件
import tool from "./utils/tool";
Vue.use(tool);
第三步
在你需要监听localStorage的文件中加入下列代码,即可实现你在组件任意位置改变localStorage某个键的值,在需要监听localStorage的组件内都能监听到值的改变,从而重新赋值,以此达到监听的目的。
注意: 监听代码写在 mounted() 中。。。
mounted() {
//解决this指向问题,在window.addEventListener中this是指向window的。
//需要将vue实例赋值给_this,这样在window.addEventListener中通过_this可以为vue实例上data中的变量赋值
let _this = this;
//根据自己需要来监听对应的key
window.addEventListener("setItemEvent", function (e) {
//e.key : 是值发生变化的key
//例如 e.key==="token";
//e.newValue : 是可以对应的新值
console.log("值改变了");
if (e.key === "token") {
console.log(e.newValue);
_this.token= JSON.parse(e.newValue);
}
});
},