forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseOption.ts
More file actions
25 lines (21 loc) · 819 Bytes
/
useOption.ts
File metadata and controls
25 lines (21 loc) · 819 Bytes
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
import optionHolder from "@service/components/option-holder"
import { onBeforeMount, type Reactive, reactive, toRaw, watch } from "vue"
type Options<T> = {
defaultValue: () => T
copy: (target: T, source: T) => void
onChange?: (newVal: T) => void
}
export const useOption = <T extends object = Partial<timer.option.AllOption>>(options: Options<T>): { option: Reactive<T> } => {
const { defaultValue, copy, onChange } = options
const option = reactive<T>(defaultValue?.())
onBeforeMount(async () => {
const currentVal = await optionHolder.get() as T
copy(option as T, currentVal)
watch(option, async () => {
const newVal = toRaw(option) as T
await optionHolder.set(newVal)
onChange?.(newVal)
})
})
return { option }
}