Skip to content

Instantly share code, notes, and snippets.

@monsat
Last active September 19, 2022 03:15
Show Gist options
  • Save monsat/4c1eca1d6ea9766b03bc5e4894fe8271 to your computer and use it in GitHub Desktop.
Save monsat/4c1eca1d6ea9766b03bc5e4894fe8271 to your computer and use it in GitHub Desktop.
useState Clone: Nuxt 3 useState composables for Nuxt 2 app
import { Ref } from 'vue'
import { createGlobalState, createSharedComposable } from '@vueuse/core'
const createBaseStore = <T>() => createGlobalState<Record<string, Ref<T>>>(() => reactive({}))
const useBaseStore = createSharedComposable(createBaseStore)
export const useState = <T>(key: string, init?: () => T): Ref<T> => {
const store = useBaseStore<T>()
const state = store[key]
if (state !== undefined) {
return state
}
const initialValue = ref(init()) as Ref<T>
store[key] = initialValue
return initialValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment