Преглед изворни кода

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

fix #1348
tangjinzhou пре 5 година
родитељ
комит
d437a0145d

+ 7 - 0
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

+ 5 - 2
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]) {