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 3 commits
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
25 changes: 25 additions & 0 deletions packages/core/useVModel/index.test.ts
Expand Up @@ -177,4 +177,29 @@ describe('useVModel', () => {

expect(emitValue instanceof SomeClass).toBeTruthy()
})

it('should be side effect free when using objects', async () => {
const emitMock = vitest.fn()

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

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

dataA.value.age = 20

await nextTick()
expect(props.person).toEqual(expect.objectContaining({ age: 18 }))

dataB.value.child.age = 3

expect(props.person).toEqual(expect.objectContaining({
child: { age: 2 },
}))
})
})
7 changes: 5 additions & 2 deletions packages/core/useVModel/index.ts
@@ -1,4 +1,5 @@
import { isDef } from '@vueuse/shared'
import type { AnyObj } from '@vueuse/shared'
import { cloneDeep, isDef, isObject } from '@vueuse/shared'
import type { UnwrapRef } from 'vue-demi'
import { computed, getCurrentInstance, isVue2, ref, watch } from 'vue-demi'

Expand Down Expand Up @@ -72,9 +73,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 })

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

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

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

describe('utils', () => {
it('increaseWithUnit', () => {
Expand All @@ -17,6 +17,20 @@ 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 @@ -105,3 +119,21 @@ 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: 20 additions & 0 deletions packages/shared/utils/index.ts
@@ -1,3 +1,6 @@
import type { AnyObj } from './types'
import { isObject } from './is'

export * from './is'
export * from './filters'
export * from './types'
Expand Down Expand Up @@ -101,3 +104,20 @@ 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) => {
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 =>
toString.call(val) === '[object Object]'
val?.constructor?.name === '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: 5 additions & 0 deletions packages/shared/utils/types.ts
Expand Up @@ -5,6 +5,11 @@ 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