| 6 | import { ref, watch, type Ref } from "vue"; |
| 7 | |
| 8 | export function useLocalStorage<T>(key: string, defaultValue: T): Ref<T> { |
| 9 | // 读取初始值 |
| 10 | const storedValue = localStorage.getItem(key); |
| 11 | const initialValue = storedValue ? JSON.parse(storedValue) : defaultValue; |
| 12 | |
| 13 | const value = ref<T>(initialValue) as Ref<T>; |
| 14 | |
| 15 | // 监听变化并保存 |
| 16 | watch( |
| 17 | value, |
| 18 | (newValue) => { |
| 19 | try { |
| 20 | localStorage.setItem(key, JSON.stringify(newValue)); |
| 21 | } catch (error) { |
| 22 | console.error(`Error saving to localStorage: ${error}`); |
| 23 | } |
| 24 | }, |
| 25 | { deep: true }, |
| 26 | ); |
| 27 | |
| 28 | // 监听其他标签页的变化 |
| 29 | if (typeof window !== "undefined") { |
| 30 | window.addEventListener("storage", (e) => { |
| 31 | if (e.key === key && e.newValue) { |
| 32 | try { |
| 33 | value.value = JSON.parse(e.newValue); |
| 34 | } catch (error) { |
| 35 | console.error(`Error parsing localStorage value: ${error}`); |
| 36 | } |
| 37 | } |
| 38 | }); |
| 39 | } |
| 40 | |
| 41 | return value; |
| 42 | } |