1.1 State – createGlobalState
https://vueuse.org/shared/createGlobalState/
作用
在全局范围内维护一个变量,以便于在vue的不同组件中使用。
官方示例
- 非持久化(数据保存在内存中)
在store.js
中使用createGlobalState
导出一个方法useGlobalState
,在其他文件中可以使用这个方法拿到数据。
// store.js
import { ref } from 'vue'
import { createGlobalState } from '@vueuse/core'
export const useGlobalState = createGlobalState(
() => {
const count = ref(0)
return { count }
}
)
// component.js
import { useGlobalState } from './store'
const { count } = useGlobalState()
-
持久化(数据保存在
localStorage
中)useStorage
是另一个hook,这里只是使用一下
// store.js
import { createGlobalState, useStorage } from '@vueuse/core'
export const useGlobalState = createGlobalState(
() => useStorage('vueuse-local-storage', 'initialValue'),
)
// component.js
import { useGlobalState } from './store'
const state = useGlobalState()
源码分析
import { effectScope } from 'vue-demi'
export type CreateGlobalStateReturn<T> = () => T
export function createGlobalState<T>(
stateFactory: () => T,
): CreateGlobalStateReturn<T> {
// 从这个变量可以看出,这个方法只能全局使用一次,如果已经初始化过一次,就直接返回。
let initialized = false
let state: T
// effectScope 是一个响应式副作用的作用域,具体细节看官网
// https://cn.vuejs.org/api/reactivity-advanced.html#effectscope
const scope = effectScope(true)
return () => {
if (!initialized) {
state = scope.run(stateFactory)!
initialized = true
}
return state
}
}