Skip to content

Commit

Permalink
feat(props): provide props to validation
Browse files Browse the repository at this point in the history
Added all props to the prop validator as a second argument

#3254
  • Loading branch information
nandi95 committed Sep 28, 2021
1 parent 467e113 commit 40b3232
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
22 changes: 22 additions & 0 deletions packages/runtime-core/__tests__/componentProps.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,28 @@ describe('component props', () => {
expect(root.innerHTML).toBe('<div id="b">2</div>')
})

test('validator arguments', async () => {
const mockFn = jest.fn((...args: any[]) => true)
const Comp = defineComponent({
props: {
foo: {
type: Number,
validator: (value, props) => mockFn(value, props)
},
bar: {
type: Number
}
},
template: `<div />`
})

// Note this one is using the main Vue render so it can compile template
// on the fly
const root = document.createElement('div')
domRender(h(Comp, { foo: 1, bar: 2 }), root)
expect(mockFn).toHaveBeenCalledWith(1, { foo: 1, bar: 2 })
})

test('warn props mutation', () => {
let instance: ComponentInternalInstance
let setupProps: any
Expand Down
6 changes: 4 additions & 2 deletions packages/runtime-core/src/componentProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export interface PropOptions<T = any, D = T> {
type?: PropType<T> | true | null
required?: boolean
default?: D | DefaultFactory<D> | null | undefined | object
validator?(value: unknown): boolean
validator?(value: unknown, props: Data): boolean
}

export type PropType<T> = PropConstructor<T> | PropConstructor<T>[]
Expand Down Expand Up @@ -575,6 +575,7 @@ function validateProps(
key,
resolvedValues[key],
opt,
resolvedValues
!hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key))
)
}
Expand All @@ -587,6 +588,7 @@ function validateProp(
name: string,
value: unknown,
prop: PropOptions,
props: Data,
isAbsent: boolean
) {
const { type, required, validator } = prop
Expand Down Expand Up @@ -616,7 +618,7 @@ function validateProp(
}
}
// custom validator
if (validator && !validator(value)) {
if (validator && !validator(value, props)) {
warn('Invalid prop: custom validator check failed for prop "' + name + '".')
}
}
Expand Down

0 comments on commit 40b3232

Please sign in to comment.