Created
November 22, 2023 06:05
-
-
Save u007/23c11dbaa9cc3d7f94986f1c57b825f5 to your computer and use it in GitHub Desktop.
localStorage composable ref
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const useLocal = <T>(field: string, defaultData: T, prefix = 'state.') => { | |
const value = ref(defaultData) | |
const name = `${prefix}${field}` | |
watch(value, (v) => { | |
// console.log('useLocal updated', name, v) | |
localStorage.setItem(name, JSON.stringify(v)) | |
}, { deep: true }) | |
if (typeof window === 'undefined') { | |
return value | |
} | |
const localData = localStorage.getItem(name) | |
if (localData) { | |
value.value = JSON.parse(localData) | |
} | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment