Vue props,加与不加 type 的区别?

作者站长头像
站长
· 阅读数 8
// Vue 2.0.0 src/core/util/props.js
function getPropDefaultValue(){
    省略
    // call factory function for non-Function types
    return typeof def === 'function' && prop.type !== Function
        ? def.call(vm)
        : def
}

const vm1 = new Vue({
    props: {
        a: {
            default: () => ({ b: 1 })
        }
    },
    propsData: {
        a: undefined
    },
    template: '<div>{{ a.b }}</div>'
}).$mount()

const vm2 = new Vue({
    props: {
        a: {
            type: Function,// 相比vm1多了这个
            default: () => ({ b: 1 })
        }
    },
    propsData: {
        a: undefined
    },
    template: '<div>{{ a.b }}</div>'
}).$mount()

vm2相比于vm1 多了个type: Function。但是在调用getPropDefaultValue时,vm1执行 def.call(vm),返回对象 {b: 1}vm2执行 def,返回函数 () => ({ b: 1 })

源码中注释写道 call factory function for non-Function types为啥要这么设计?就算不添加 type: Function, default的内容不也是函数吗?

回复
1个回答
avatar
test
2024-06-30

题主最后一句有误区:不添加 type: Function 指定类型, default 的内容就 不是 函数了,而是执行 def.call(vm) 返回对象 { b: 1 },比如 vm1

指定了类型,那么 prop.type !== Function 就会返回 false ,就直接返回这个函数了,比如 vm2 。如果不指定类型,那就会返回 true,也就像 vm1 那样得到一个对象了

call factory function for non-Function types 是指为 非函数 类型的值调用工厂函数,这个设计规则主要针对 没有 指定类型 默认值是可执行表达式(如箭头函数)情况下使用工厂函数获取 props 的正确默认值。

【补充】简述流程

  • default 不为函数类型

    • typeof def === 'function'false,直接返回默认值
  • default 为函数

    • 不设置 type: Function

      • prop.type !== Functionfalse
      • def.call(vm) 执行箭头函数,得到返回值 { b: 1 }
    • 设置 type: Function

      • prop.type !== Functiontrue,不执行直接返回(也就是这个箭头函数)
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容