Skip to content

createGlobalState

类别
导出体积
125 B
上次更改
3 minutes ago
相关

将状态保留在全局范围内,以便在 Vue 实例之间重复使用。

示例

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

用法

无持久性 (存储在内存中)

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

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

更大的示例:

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

export const useGlobalState = createGlobalState(
  () => {
    // 状态
    const count = ref(0)

    // 计算属性
    const doubleCount = computed(() => count.value * 2)

    // 动作
    function increment() {
      count.value++
    }

    return { count, doubleCount, increment }
  }
)

使用持久性

使用 useStorage 将数据存储在 localStorage 中:

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
/**
 * 在全局范围内保留状态,以便在 Vue 实例之间重复使用。
 *
 * @see https://vueuse.org/createGlobalState
 * @param stateFactory 用于创建状态的工厂函数
 */
export declare function createGlobalState<Fn extends AnyFn>(
  stateFactory: Fn,
): Fn

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
童欧巴
JD Solanki
Ducz01
Tobi
thefeymesaleng
plylrnsdy
wheat
Preston Alvarado
jelf

更新日志

v10.0.0-beta.0 on 3/14/2023
f21b2 - feat: allow passing initial args (#2790)