From d437a0145df5b63a959da873041816af68b440db Mon Sep 17 00:00:00 2001 From: tangjinzhou <415800467@qq.com> Date: Fri, 12 Jun 2020 21:06:28 +0800 Subject: [PATCH] fix(runtime-core): default value for function type prop (#1349) fix #1348 --- packages/runtime-core/__tests__/componentProps.spec.ts | 7 +++++++ packages/runtime-core/src/componentProps.ts | 7 +++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/runtime-core/__tests__/componentProps.spec.ts b/packages/runtime-core/__tests__/componentProps.spec.ts index 59167ea5351..fb701d2bd2f 100644 --- a/packages/runtime-core/__tests__/componentProps.spec.ts +++ b/packages/runtime-core/__tests__/componentProps.spec.ts @@ -158,6 +158,7 @@ describe('component props', () => { test('default value', () => { let proxy: any const defaultFn = jest.fn(() => ({ a: 1 })) + const defaultBaz = jest.fn(() => ({ b: 1 })) const Comp = { props: { @@ -166,6 +167,10 @@ describe('component props', () => { }, bar: { default: defaultFn + }, + baz: { + type: Function, + default: defaultBaz } }, render() { @@ -178,7 +183,9 @@ describe('component props', () => { expect(proxy.foo).toBe(2) const prevBar = proxy.bar expect(proxy.bar).toEqual({ a: 1 }) + expect(proxy.baz).toEqual(defaultBaz) expect(defaultFn).toHaveBeenCalledTimes(1) + expect(defaultBaz).toHaveBeenCalledTimes(0) // #999: updates should not cause default factory of unchanged prop to be // called again diff --git a/packages/runtime-core/src/componentProps.ts b/packages/runtime-core/src/componentProps.ts index 5d3cef7e39d..0f6fecb14e6 100644 --- a/packages/runtime-core/src/componentProps.ts +++ b/packages/runtime-core/src/componentProps.ts @@ -270,13 +270,16 @@ function resolvePropValue( key: string, value: unknown ) { - const opt = options[key] + const opt = options[key] as any if (opt != null) { const hasDefault = hasOwn(opt, 'default') // default values if (hasDefault && value === undefined) { const defaultValue = opt.default - value = isFunction(defaultValue) ? defaultValue() : defaultValue + value = + opt.type !== Function && isFunction(defaultValue) + ? defaultValue() + : defaultValue } // boolean casting if (opt[BooleanFlags.shouldCast]) {