/
index.ts
42 lines (35 loc) · 890 Bytes
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { createApp, reactive } from 'vue-demi'
import { defaultDocument } from '../_configurable'
function withScope<T extends object>(factory: () => T): T {
let state: T = null as any
const document = defaultDocument
if (document) {
const container = document.createElement('div')
createApp({
setup() {
state = reactive(factory()) as T
},
render: () => null,
}).mount(container)
}
else {
state = reactive(factory()) as T
}
return state
}
/**
* 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 function createGlobalState<T extends object>(
stateFactory: () => T,
) {
let state: T
return () => {
if (state == null)
state = withScope(stateFactory)
return state
}
}