方法
我们需要重写 localStorage 下的所有方法,以便无论何时使用它们都可以被观察到。这就需要一个事件机制来进行消息传递。
由于 Vue 3 删除了和emit 事件接口,我们可以使用 mitt 或 tiny-emitter 等第三方库来实现此功能。
不过,我打算使用自己实现的中介模式作为通信方法。
解决方案
使用中介者模式的实现解决方案。
// mediator.ts
export interface MediatorProps {
uuid?: number;
publish?: (topic: string, ...args: unknown[]) => void;
subscribe?: (topic: string, callback: (...args: unknown[]) => void) => void;
}
const mediator = (function () {
let topics = [],
uuid = 0;
function subscribe(topic: string, callback: (...args: unknown[]) => void) {
uuid++;
topics[topic] = topics[topic]
? [...topics[topic], { callback, uuid }]
: [{ callback, uuid }];
}
function publish(topic: string, ...args: unknown[]) {
if (topics[topic]) {
topics[topic].map((item) => item.callback(...args));
}
}
return {
install: function (obj: MediatorProps) {
obj.uuid = uuid;
obj.publish = publish;
obj.subscribe = subscribe;
return obj;
},
};
})();
export default mediator;
然后我重写 localStorage 函数。
// localStorage.ts
import mediator from "./mediator";
const keys: string[] = [];
const createMediator = () => mediator.install({});
const sub = createMediator();
export const $localStorage = {
getItem: (key: string) => {
return window.localStorage.getItem(key);
},
setItem: (key: string, value: any) => {
// 防止重复发布
if (!keys.includes(key)) keys.push(key);
// 发布事件(如果已修改)
sub.publish(key, value);
window.localStorage.setItem(key, value);
},
clear: () => {
// 为每个键清除时发布一个事件
keys.map((key) => sub.publish(key, undefined));
// 发布后,清除记录键值的数组
keys.length = 0;
window.localStorage.clear();
},
removeItem: (key: string) => {
keys.splice(keys.indexOf(key), 1);
// 删除时,发布undefined
sub.publish(key, undefined);
window.localStorage.removeItem(key);
},
key: window.localStorage.key,
length: window.localStorage.length,
};
第三,我实现了 useStorage 钩子
// useStorage.ts
import { ref } from "vue";
import mediator from "./mediator";
const createMediator = () => mediator.install({});
export const useStorage = (key: string) => {
const string = ref(null);
const sub = createMediator();
sub.subscribe(key, (value) => string.value = value);
return string;
};
第四,我写的测试代码是这样的:
// One.vue
// use localStorage
import { watch } from "vue";
import { useStorage } from "./hook";
const key = useStorage("imodd");
watch([key], (a) => console.log(a));
// Two.vue
// Observe localStorage
然后,结果是这样的
图片
好了,这就是全部了。希望这篇文章能给你带来一点帮助。
https://javascript.plainenglish.io/how-to-elegantly-observe-localstorage-changes-in-vue-3-a42fcf9c82ca