主题
createGlobalState
将状态保留在全局范围内,以便可以跨 Vue 实例重用。
🌐 Keep states in the global scope to be reusable across Vue instances.
示例
用法
🌐 Usage
没有持久性(存储在内存中)
🌐 Without Persistence (Store in Memory)
ts
// store.ts
import { createGlobalState } from '@vueuse/core'
import { shallowRef } from 'vue'
export const useGlobalState = createGlobalState(
() => {
const count = shallowRef(0)
return { count }
}
)一个更大的例子:
🌐 A bigger example:
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 }
}
)使用持久性
🌐 With Persistence
存储在 localStorage 与 useStorage 中:
🌐 Store in localStorage with useStorage:
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 }
},
})