Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useVModel): support clone option #2022

Merged
merged 8 commits into from Sep 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 32 additions & 5 deletions packages/core/useVModel/index.test.ts
Expand Up @@ -178,7 +178,7 @@ describe('useVModel', () => {
expect(emitValue instanceof SomeClass).toBeTruthy()
})

it('should be side effect free when using objects', async () => {
it('should clone object', async () => {
antfu marked this conversation as resolved.
Show resolved Hide resolved
const emitMock = vitest.fn()

const props = {
Expand All @@ -188,18 +188,45 @@ describe('useVModel', () => {
},
}

const dataA = useVModel(props, 'person', emitMock, { passive: true })
const dataB = useVModel(props, 'person', emitMock, { passive: true, deep: true })
const data = useVModel(props, 'person', emitMock, { passive: true, clone: true })
const dataDeep = useVModel(props, 'person', emitMock, { passive: true, clone: true, deep: true })

dataA.value.age = 20
data.value.age = 20

await nextTick()
expect(props.person).not.toBe(data.value)
expect(props.person).toEqual(expect.objectContaining({ age: 18 }))

dataB.value.child.age = 3
dataDeep.value.child.age = 3

expect(props.person).not.toBe(dataDeep.value)
expect(props.person).toEqual(expect.objectContaining({
child: { age: 2 },
}))
})

it('should deep clone object with clone function', async () => {
const emitMock = vitest.fn()
const clone = vitest.fn(x => JSON.parse(JSON.stringify(x)))

const props = {
person: {
age: 18,
child: { age: 2 },
},
}

const data = useVModel(props, 'person', emitMock, { passive: true, clone, deep: true })

data.value.age = 20
data.value.child.age = 3

await nextTick()
expect(clone).toHaveBeenCalled()
expect(props.person).not.toBe(data.value)
expect(props.person).toEqual({
age: 18,
child: { age: 2 },
})
})
})
19 changes: 15 additions & 4 deletions packages/core/useVModel/index.ts
@@ -1,8 +1,9 @@
import type { AnyObj } from '@vueuse/shared'
import { cloneDeep, isDef, isObject } from '@vueuse/shared'
import { isDef, isFunction } from '@vueuse/shared'
import type { UnwrapRef } from 'vue-demi'
import { computed, getCurrentInstance, isVue2, ref, watch } from 'vue-demi'

export type CloneFn<F, T = F> = (x: F) => T

export interface UseVModelOptions<T> {
/**
* When passive is set to `true`, it will use `watch` to sync with props and ref.
Expand Down Expand Up @@ -30,8 +31,17 @@ export interface UseVModelOptions<T> {
* @default undefined
*/
defaultValue?: T
/**
* Clone when getting the value from props, shortcut for: JSON.parse(JSON.stringify(value)).
* Default to false
*
* @default false
*/
clone?: boolean | CloneFn<T>
}

const defaultCloneFn = <F, T = F>(v: F): T => JSON.parse(JSON.stringify(v))

/**
* Shorthand for v-model binding, props + emit -> ref
*
Expand All @@ -47,6 +57,7 @@ export function useVModel<P extends object, K extends keyof P, Name extends stri
options: UseVModelOptions<P[K]> = {},
) {
const {
clone = false,
passive = false,
eventName,
deep = false,
Expand All @@ -73,11 +84,11 @@ export function useVModel<P extends object, K extends keyof P, Name extends stri
event = eventName || event || `update:${key!.toString()}`

const getValue = () => isDef(props[key!]) ? props[key!] : defaultValue
const cloneObj = (obj: AnyObj) => deep ? cloneDeep(obj) : ({ ...obj })
const cloneFn = (val: P[K]) => isFunction(clone) ? clone(val) : defaultCloneFn(val)

if (passive) {
const initialValue = getValue()
const proxy = ref<P[K]>(isObject(initialValue) ? cloneObj(initialValue) : initialValue!)
const proxy = ref<P[K]>(clone && initialValue ? cloneFn(initialValue) : initialValue!)

watch(() => props[key!], v => proxy.value = v as UnwrapRef<P[K]>)

Expand Down
34 changes: 1 addition & 33 deletions packages/shared/utils/index.test.ts
@@ -1,5 +1,5 @@
import { ref } from 'vue-demi'
import { cloneDeep, createFilterWrapper, debounceFilter, increaseWithUnit, isObject, objectPick, throttleFilter } from '.'
import { createFilterWrapper, debounceFilter, increaseWithUnit, objectPick, throttleFilter } from '.'

describe('utils', () => {
it('increaseWithUnit', () => {
Expand All @@ -17,20 +17,6 @@ describe('utils', () => {
expect(objectPick({ a: 1, b: 2, c: 3 }, ['a', 'b'])).toEqual({ a: 1, b: 2 })
expect(objectPick({ a: 1, b: 2, c: undefined }, ['a', 'b'], true)).toEqual({ a: 1, b: 2 })
})

it('cloneDeep', () => {
const obj = {
a: 1,
b: 2,
d: {
e: 3,
f: { g: 4 },
},
}

expect(cloneDeep(obj)).toEqual(obj)
expect(cloneDeep(obj)).not.toBe(obj)
})
})

describe('filters', () => {
Expand Down Expand Up @@ -119,21 +105,3 @@ describe('filters', () => {
expect(debouncedFilterSpy).toHaveBeenCalledTimes(1)
})
})

describe('is', () => {
it('isObject', () => {
expect(isObject({})).toBe(true)
expect(isObject(Object.create({}))).toBe(true)
expect(isObject([])).toBe(false)
expect(isObject(1)).toBe(false)
expect(isObject('1')).toBe(false)
expect(isObject(true)).toBe(false)
expect(isObject(null)).toBe(false)
expect(isObject(undefined)).toBe(false)
expect(isObject(() => {})).toBe(false)
expect(isObject(/a/)).toBe(false)
expect(isObject(new Date())).toBe(false)
expect(isObject(new Map())).toBe(false)
expect(isObject(new Set())).toBe(false)
})
})
20 changes: 0 additions & 20 deletions packages/shared/utils/index.ts
@@ -1,6 +1,3 @@
import type { AnyObj } from './types'
import { isObject } from './is'

export * from './is'
export * from './filters'
export * from './types'
Expand Down Expand Up @@ -104,20 +101,3 @@ export function objectPick<O, T extends keyof O>(obj: O, keys: T[], omitUndefine
return n
}, {} as Pick<O, T>)
}

/**
* Simple recursive deep clone
*
* @category Object
*/
export const cloneDeep = (obj: any) => {
antfu marked this conversation as resolved.
Show resolved Hide resolved
if (!isObject(obj))
return obj

const clone: AnyObj = {}

for (const key in obj)
clone[key] = cloneDeep((obj as AnyObj)[key])

return clone
}
2 changes: 1 addition & 1 deletion packages/shared/utils/is.ts
Expand Up @@ -10,7 +10,7 @@ export const isFunction = <T extends Function> (val: any): val is T => typeof va
export const isNumber = (val: any): val is number => typeof val === 'number'
export const isString = (val: unknown): val is string => typeof val === 'string'
export const isObject = (val: any): val is object =>
val?.constructor?.name === 'Object'
toString.call(val) === '[object Object]'
export const isWindow = (val: any): val is Window =>
typeof window !== 'undefined' && toString.call(val) === '[object Window]'
export const now = () => Date.now()
Expand Down
5 changes: 0 additions & 5 deletions packages/shared/utils/types.ts
Expand Up @@ -5,11 +5,6 @@ import type { Ref, WatchOptions, WatchSource } from 'vue-demi'
*/
export type Fn = () => void

/**
* Any object
*/
export type AnyObj = Record<string | symbol, any>

/**
* A ref that allow to set null or undefined
*/
Expand Down