跳到主要内容

createGlobalState

分类
导出大小
152 B
最后更改
4 个月前
相关

将状态保存在全局作用域中,以便在 Vue 实例之间重用。

演示

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

用法

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

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

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

一个更大的例子

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

export const useGlobalState = createGlobalState(
  () => {
    // state
    const count = shallowRef(0)

    // getters
    const doubleCount = computed(() => count.value * 2)

    // actions
    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
/**
 * Keep states in the global scope to be reusable across Vue instances.
 *
 * @see https://vueuse.org.cn/createGlobalState
 * @param stateFactory A factory function to create the state
 */
export declare function createGlobalState<Fn extends AnyFn>(
  stateFactory: Fn,
): Fn

源码

源码演示文档

贡献者

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

更新日志

v12.0.0-beta.1 于 11/21/2024
0a9ed - feat!: 移除 Vue 2 支持,优化 bundle 并清理代码 (#4349)
v10.0.0-beta.0 于 3/14/2023
f21b2 - feat: 允许传入初始参数 (#2790)

在 MIT 许可证下发布。