Skip to content

Commit 40b3232

Browse files
committed
feat(props): provide props to validation
Added all props to the prop validator as a second argument #3254
1 parent 467e113 commit 40b3232

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

packages/runtime-core/__tests__/componentProps.spec.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,28 @@ describe('component props', () => {
278278
expect(root.innerHTML).toBe('<div id="b">2</div>')
279279
})
280280

281+
test('validator arguments', async () => {
282+
const mockFn = jest.fn((...args: any[]) => true)
283+
const Comp = defineComponent({
284+
props: {
285+
foo: {
286+
type: Number,
287+
validator: (value, props) => mockFn(value, props)
288+
},
289+
bar: {
290+
type: Number
291+
}
292+
},
293+
template: `<div />`
294+
})
295+
296+
// Note this one is using the main Vue render so it can compile template
297+
// on the fly
298+
const root = document.createElement('div')
299+
domRender(h(Comp, { foo: 1, bar: 2 }), root)
300+
expect(mockFn).toHaveBeenCalledWith(1, { foo: 1, bar: 2 })
301+
})
302+
281303
test('warn props mutation', () => {
282304
let instance: ComponentInternalInstance
283305
let setupProps: any

packages/runtime-core/src/componentProps.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ export interface PropOptions<T = any, D = T> {
5656
type?: PropType<T> | true | null
5757
required?: boolean
5858
default?: D | DefaultFactory<D> | null | undefined | object
59-
validator?(value: unknown): boolean
59+
validator?(value: unknown, props: Data): boolean
6060
}
6161

6262
export type PropType<T> = PropConstructor<T> | PropConstructor<T>[]
@@ -575,6 +575,7 @@ function validateProps(
575575
key,
576576
resolvedValues[key],
577577
opt,
578+
resolvedValues
578579
!hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key))
579580
)
580581
}
@@ -587,6 +588,7 @@ function validateProp(
587588
name: string,
588589
value: unknown,
589590
prop: PropOptions,
591+
props: Data,
590592
isAbsent: boolean
591593
) {
592594
const { type, required, validator } = prop
@@ -616,7 +618,7 @@ function validateProp(
616618
}
617619
}
618620
// custom validator
619-
if (validator && !validator(value)) {
621+
if (validator && !validator(value, props)) {
620622
warn('Invalid prop: custom validator check failed for prop "' + name + '".')
621623
}
622624
}

0 commit comments

Comments
 (0)