fix(runtime-core): default value for function type prop (#1349)

fix #1348
This commit is contained in:
tangjinzhou 2020-06-12 21:06:28 +08:00 committed by GitHub
parent 4c4f39b6ea
commit d437a0145d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 2 deletions

View File

@ -158,6 +158,7 @@ describe('component props', () => {
test('default value', () => { test('default value', () => {
let proxy: any let proxy: any
const defaultFn = jest.fn(() => ({ a: 1 })) const defaultFn = jest.fn(() => ({ a: 1 }))
const defaultBaz = jest.fn(() => ({ b: 1 }))
const Comp = { const Comp = {
props: { props: {
@ -166,6 +167,10 @@ describe('component props', () => {
}, },
bar: { bar: {
default: defaultFn default: defaultFn
},
baz: {
type: Function,
default: defaultBaz
} }
}, },
render() { render() {
@ -178,7 +183,9 @@ describe('component props', () => {
expect(proxy.foo).toBe(2) expect(proxy.foo).toBe(2)
const prevBar = proxy.bar const prevBar = proxy.bar
expect(proxy.bar).toEqual({ a: 1 }) expect(proxy.bar).toEqual({ a: 1 })
expect(proxy.baz).toEqual(defaultBaz)
expect(defaultFn).toHaveBeenCalledTimes(1) expect(defaultFn).toHaveBeenCalledTimes(1)
expect(defaultBaz).toHaveBeenCalledTimes(0)
// #999: updates should not cause default factory of unchanged prop to be // #999: updates should not cause default factory of unchanged prop to be
// called again // called again

View File

@ -270,13 +270,16 @@ function resolvePropValue(
key: string, key: string,
value: unknown value: unknown
) { ) {
const opt = options[key] const opt = options[key] as any
if (opt != null) { if (opt != null) {
const hasDefault = hasOwn(opt, 'default') const hasDefault = hasOwn(opt, 'default')
// default values // default values
if (hasDefault && value === undefined) { if (hasDefault && value === undefined) {
const defaultValue = opt.default const defaultValue = opt.default
value = isFunction(defaultValue) ? defaultValue() : defaultValue value =
opt.type !== Function && isFunction(defaultValue)
? defaultValue()
: defaultValue
} }
// boolean casting // boolean casting
if (opt[BooleanFlags.shouldCast]) { if (opt[BooleanFlags.shouldCast]) {