Skip to content

createGlobalState ​

Category
Export Size
125 B
Last Changed
last month
Related

Keep states in the global scope to be reusable across Vue instances.

Demo ​

name: 'Banana'
color: 'Yellow'
size: 'Medium'

Usage ​

Without Persistence (Store in Memory) ​

js
import { createGlobalState } from '@vueuse/core'
// store.js
import { ref } from 'vue'

export const useGlobalState = createGlobalState(
  () => {
    const count = ref(0)
    return { count }
  }
)

A bigger example:

js
import { createGlobalState } from '@vueuse/core'
// store.js
import { computed, ref } from 'vue'

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

js
// store.js
import { createGlobalState, useStorage } from '@vueuse/core'

export const useGlobalState = createGlobalState(
  () => useStorage('vueuse-local-storage', 'initialValue'),
)
js
// component.js
import { useGlobalState } from './store'

export default defineComponent({
  setup() {
    const state = useGlobalState()
    return { state }
  },
})

Type Declarations ​

typescript
/**
 * 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 ​

Source • Demo • Docs

Contributors ​

Anthony Fu
Anthony Fu
童欧巴
JD Solanki
Ducz01
Tobi
thefeymesaleng
plylrnsdy
wheat
Preston Alvarado
jelf

Changelog ​

v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.0.0-beta.0 on 3/14/2023
f21b2 - feat: allow passing initial args (#2790)

Released under the MIT License.