Skip to content

createGlobalState

Category
Export Size
125 B
Last Changed
15 minutes ago
Related

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

Demo

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

Source

SourceDemoDocs

贡献者

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)

Released under the MIT License.