createGlobalState
将状态保存在全局作用域中,以便在 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
源码
贡献者
更新日志
v12.0.0-beta.1
于 11/21/2024v10.0.0-beta.0
于 3/14/2023