Created
May 14, 2023 14:08
-
-
Save monsat/ffa9bb9a9ec3983391f41669393a2ede to your computer and use it in GitHub Desktop.
Nuxt useState with VueUse useStorage composables
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
import { useStorage } from '@vueuse/core' | |
export const useStoredState = <T>(key: string, initValue: T) => { | |
const shared = useState<T>(key, () => initValue) | |
const stored = useStorage<T>(key, initValue) | |
const state = computed({ | |
get: () => shared.value, | |
set: (value: T) => { | |
shared.value = value | |
stored.value = value | |
}, | |
}) | |
// call read() onMounted in app.vue | |
const read = () => { | |
state.value = stored.value | |
} | |
return { | |
state, | |
read, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment