主题
createGlobalState
将状态保留在全局范围内,以便可以跨 Vue 实例重用。
¥Keep states in the global scope to be reusable across Vue instances.
示例
name: 'Banana'
color: 'Yellow'
size: 'Medium'
用法
¥Usage
没有持久性(存储在内存中)
¥Without Persistence (Store in Memory)
js
import { createGlobalState } from '@vueuse/core'
// store.js
import { ref } from 'vue'
export const useGlobalState = createGlobalState(
() => {
const count = ref(0)
return { count }
}
)
一个更大的例子:
¥A bigger example:
js
import { createGlobalState } from '@vueuse/core'
// store.js
import { computed, ref } from 'vue'
export const useGlobalState = createGlobalState(
() => {
// state
const count = ref(0)
// getters
const doubleCount = computed(() => count.value * 2)
// actions
function increment() {
count.value++
}
return { count, doubleCount, increment }
}
)
使用持久性
¥With Persistence
与 useStorage
一起存储在 localStorage
中:
¥Store in localStorage
with useStorage
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/createGlobalState
* @param stateFactory A factory function to create the state
*/
export declare function createGlobalState<Fn extends AnyFn>(
stateFactory: Fn,
): Fn