forked from vueuse/vueuse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
41 lines (34 loc) · 1.09 KB
/
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
import type { MaybeRef } from '@vueuse/shared'
import type { WatchOptions } from 'vue-demi'
import { isRef, ref, unref, watch } from 'vue-demi'
export interface UseClonedOptions<T extends Record<any, any> = Record<any, any>> {
/**
* sync source only by function
*/
manual?: boolean
/**
* Custom clone function should return new value for cloned data
*/
cloneFunction?: (source: T, cloned: T) => T
/**
* Options for watcher
*
* @default { immediate: true, deep: true }
*/
watchOptions?: WatchOptions
}
export function useCloned<T extends Record<any, any> = Record<any, any>>(source: MaybeRef<T>, options: UseClonedOptions = {}) {
const cloned = ref<T>({} as T)
const { manual, cloneFunction, watchOptions = { immediate: true, deep: true } } = options
if (!manual && isRef(source))
watch(source, sync, watchOptions)
else
sync()
function defaultCloning() {
return JSON.parse(JSON.stringify(unref(source)))
}
function sync() {
cloned.value = cloneFunction ? cloneFunction(unref(source), cloned.value) : defaultCloning()
}
return { cloned, sync }
}