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

fix: ignore prototype methods when using setData on objects #2265

Merged
merged 2 commits into from
Dec 4, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,25 @@ export function mergeGlobalProperties(
export const isObject = (obj: unknown): obj is Record<string, any> =>
!!obj && typeof obj === 'object'

function isClass(obj: unknown) {
if (!(obj instanceof Object)) return

const isCtorClass =
obj.constructor && obj.constructor.toString().substring(0, 5) === 'class'

if (!('prototype' in obj)) {
return isCtorClass
}

const prototype = obj.prototype as any
const isPrototypeCtorClass =
prototype.constructor &&
prototype.constructor.toString &&
prototype.constructor.toString().substring(0, 5) === 'class'

return isCtorClass || isPrototypeCtorClass
}

// https://stackoverflow.com/a/48218209
export const mergeDeep = (
target: Record<string, unknown>,
Expand All @@ -80,8 +99,13 @@ export const mergeDeep = (
if (!isObject(target) || !isObject(source)) {
return source
}

Object.keys(source)
.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(source) ?? {}))
.concat(
isClass(source)
? Object.getOwnPropertyNames(Object.getPrototypeOf(source) ?? {})
: Object.getOwnPropertyNames(source)
)
.forEach((key) => {
const targetValue = target[key]
const sourceValue = source[key]
Expand Down
29 changes: 29 additions & 0 deletions tests/setData.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,4 +246,33 @@ describe('setData', () => {

expect(wrapper.vm.getResult()).toStrictEqual(`test2: ${expectedResult}`)
})

it('should be possible to replace a primitive value with another', async () => {
Haberkamp marked this conversation as resolved.
Show resolved Hide resolved
const wrapper = mount(
defineComponent({
template: '<div />',
data() {
return {
firstArray: [],
secondArray: []
}
}
})
)

await wrapper.setData({
firstArray: [],
secondArray: []
Haberkamp marked this conversation as resolved.
Show resolved Hide resolved
})

expect(wrapper.vm.$data).toStrictEqual({
firstArray: [],
secondArray: []
})

expect(Object.keys(wrapper.vm.$data)).toStrictEqual([
'firstArray',
'secondArray'
])
Haberkamp marked this conversation as resolved.
Show resolved Hide resolved
})
})