forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseShadow.ts
More file actions
12 lines (11 loc) · 921 Bytes
/
useShadow.ts
File metadata and controls
12 lines (11 loc) · 921 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
import { type Ref, type WatchSource, ref, watch } from "vue"
export function useShadow<T>(source: WatchSource<T>): [Ref<T>, setter: (val: T) => void, refresh: () => void]
export function useShadow<T>(source: WatchSource<T>, defaultValue: T): [Ref<T>, setter: (val: T) => void, refresh: () => void]
export function useShadow<T>(source: WatchSource<T>, defaultValue?: T): [Ref<T | undefined>, setter: (val?: T) => void, refresh: () => void]
export function useShadow<T>(source: WatchSource<T>, defaultValue?: T): [Ref<T | undefined>, setter: (val?: T) => void, refresh: () => void] {
const getVal = () => typeof source === "function" ? source() : source?.value
const initial = getVal() ?? defaultValue
const shadow = initial ? ref<T>(initial) : ref<T>()
watch(source, () => shadow.value = getVal())
return [shadow as Ref<T | undefined>, (val?: T) => shadow.value = val, () => shadow.value = getVal()]
}