Vue3 優雅地監聽 localStorage 變化
最近在研究框架,也仔細用了Vue3
一些功能,今天分享一次我的實踐:
「Vue3
如何監聽localStorage
的變化。」
💡 爲什麼要這樣做?
原生的localStorage
只能監聽同源地址下不同頁面的localStorage
變化,作爲單頁面應用,顯然不實用。所以我打算自定義一個hook
監聽localStorage
的變化。
💎 思路
首先我們需要重寫localStorage
下的所有方法,這樣在每個方法被使用的時候就可以被監聽到了。
此時就需要一個事件機制,用於傳遞消息。
在Vue3
移除了$on
、$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: () => {
// 被刪除就每個key發佈事件
keys.map((key) => sub.publish(key, undefined));
// 發佈後清空記錄key的數組
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 hook
// 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;
};
💎 測試
🚗 使用localStorage
// One.vue
// 使用localStorage
import { watch } from "vue";
import { useStorage } from "./hook";
const key = useStorage("yourKey");
watch([key], (a) => console.log(a));
🚗 監聽localStorage
變化
// Two.vue
// 監聽localStorage
<script setup lang="ts">
import { ref } from "vue";
import { localStorage } from "./hook";
const count = ref(0);
</script>
<template>
<div>
<button
type="button"
@click="$localStorage.setItem('a', count++);"
>
count is {{ count }}
</button>
</div>
</template>
🚗 結果
好了今天的分享的就到了,希望今天的分享可以幫助到你!
源碼點這裏:https://codesandbox.io/p/sandbox/hardcore-hodgkin-qp5lwu
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/8DL6Gf2hrTWmxlL4w-HmIA