createGlobalState
在全局范围内保持状态,以便在 Vue 实例之间重用。
演示
name: Banana
color: Yellow
size: Medium
用法
无持久化 (存储在内存中)
ts
// store.ts
import { createGlobalState } from '@vueuse/core'
import { shallowRef } from 'vue'
export const useGlobalState = createGlobalState(
() => {
const count = shallowRef(0)
return { count }
}
)一个更大的示例
ts
// store.ts
import { createGlobalState } from '@vueuse/core'
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 中
ts
// store.ts
import { createGlobalState, useStorage } from '@vueuse/core'
export const useGlobalState = createGlobalState(
() => useStorage('vueuse-local-storage', 'initialValue'),
)ts
// component.ts
import { useGlobalState } from './store'
export default defineComponent({
setup() {
const state = useGlobalState()
return { state }
},
})类型声明
ts
export type CreateGlobalStateReturn<Fn extends AnyFn = AnyFn> = Fn
/**
* 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
*
* @__NO_SIDE_EFFECTS__
*/
export declare function createGlobalState<Fn extends AnyFn>(
stateFactory: Fn,
): CreateGlobalStateReturn<Fn>