Skip to content

Commit

Permalink
fix(runtime-core): default value for function type prop (#1349)
Browse files Browse the repository at this point in the history
fix #1348
  • Loading branch information
tangjinzhou authored Jun 12, 2020
1 parent 4c4f39b commit d437a01
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
7 changes: 7 additions & 0 deletions packages/runtime-core/__tests__/componentProps.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -166,6 +167,10 @@ describe('component props', () => {
},
bar: {
default: defaultFn
},
baz: {
type: Function,
default: defaultBaz
}
},
render() {
Expand All @@ -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
Expand Down
7 changes: 5 additions & 2 deletions packages/runtime-core/src/componentProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]) {
Expand Down

0 comments on commit d437a01

Please sign in to comment.