On this page
createGlobalState
Category | State |
---|---|
Export Size | 125 B |
Last Changed | last month |
Related | createSharedComposable |
Keep states in the global scope to be reusable across Vue instances.
Usage
Without Persistence (Store in Memory)
// store.js
import { ref } from 'vue'
import { createGlobalState } from '@vueuse/core'
export const useGlobalState = createGlobalState(
() => {
const count = ref(0)
return { count }
}
)
A bigger example:
// store.js
import { computed, ref } from 'vue'
import { createGlobalState } from '@vueuse/core'
export const useGlobalState = createGlobalState(
() => {
// state
const count = ref(0)
// getters
const doubleCount = computed(() => count.value * 2)
// actions
function increment() {
count.value++
}
return { count, doubleCount, increment }
}
)
With Persistence
Store in localStorage
with useStorage()
:
// store.js
import { createGlobalState, useStorage } from '@vueuse/core'
export const useGlobalState = createGlobalState(
() => useStorage('vueuse-local-storage', 'initialValue'),
)
// component.js
import { useGlobalState } from './store'
export default defineComponent({
setup() {
const state = useGlobalState()
return { state }
},
})
Type Declarations
/**
* Keep states in the global scope to be reusable across Vue instances.
*
* @see https://vueuse.org/createGlobalState
* @param stateFactory A factory function to create the state
*/
export declare function createGlobalState<Fn extends AnyFn>(
stateFactory: Fn
): Fn
Source
© 2019-present Anthony Fu
Licensed under the MIT License.
https://vueuse.org/shared/createGlobalState/