|
| 1 | +import type { Ref, UnwrapRef } from 'vue'; |
| 2 | +import { toRaw } from 'vue'; |
| 3 | +import { watchEffect } from 'vue'; |
| 4 | +import { unref } from 'vue'; |
| 5 | +import { watch } from 'vue'; |
| 6 | +import { ref } from 'vue'; |
| 7 | + |
| 8 | +export default function useMergedState<T, R = Ref<T>>( |
| 9 | + defaultStateValue: T | (() => T), |
| 10 | + option?: { |
| 11 | + defaultValue?: T | (() => T); |
| 12 | + value?: Ref<T> | Ref<UnwrapRef<T>>; |
| 13 | + onChange?: (val: T, prevValue: T) => void; |
| 14 | + postState?: (val: T) => T; |
| 15 | + }, |
| 16 | +): [R, (val: T) => void] { |
| 17 | + const { defaultValue, value = ref() } = option || {}; |
| 18 | + let initValue: T = |
| 19 | + typeof defaultStateValue === 'function' ? (defaultStateValue as any)() : defaultStateValue; |
| 20 | + if (value.value !== undefined) { |
| 21 | + initValue = unref(value as any) as T; |
| 22 | + } |
| 23 | + if (defaultValue !== undefined) { |
| 24 | + initValue = typeof defaultValue === 'function' ? (defaultValue as any)() : defaultValue; |
| 25 | + } |
| 26 | + |
| 27 | + const innerValue = ref(initValue) as Ref<T>; |
| 28 | + const mergedValue = ref(initValue) as Ref<T>; |
| 29 | + watchEffect(() => { |
| 30 | + let val = value.value !== undefined ? value.value : innerValue.value; |
| 31 | + if (option.postState) { |
| 32 | + val = option.postState(val as T); |
| 33 | + } |
| 34 | + mergedValue.value = val as T; |
| 35 | + }); |
| 36 | + |
| 37 | + function triggerChange(newValue: T) { |
| 38 | + const preVal = mergedValue.value; |
| 39 | + innerValue.value = newValue; |
| 40 | + if (toRaw(mergedValue.value) !== newValue && option.onChange) { |
| 41 | + option.onChange(newValue, preVal); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + // Effect of reset value to `undefined` |
| 46 | + watch(value, () => { |
| 47 | + innerValue.value = value.value as T; |
| 48 | + }); |
| 49 | + |
| 50 | + return [mergedValue as unknown as R, triggerChange]; |
| 51 | +} |
0 commit comments