Skip to content

createGlobalState

将状态保留在全局范围内,以便可以跨 Vue 实例重用。

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

示例

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

用法

¥Usage

没有持久性(存储在内存中)

¥Without Persistence (Store in Memory)

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

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

一个更大的例子:

¥A bigger example:

js
// 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

useStorage 一起存储在 localStorage 中:

¥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 }
  },
})

类型声明

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

源代码

源代码示例文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号