Vue的props中的数组和对象的default为什么要用工厂函数来返回?

584 阅读1分钟

背景

这几天在看Vue2的源码,发现了这个代码

function getPropDefaultValue (vm: ?Component, prop: PropOptions, key: string): any {
    // ...
    if (process.env.NODE_ENV !== 'production' && isObject(def)) {
        warn(
          'Invalid default value for prop "' + key + '": ' +
          'Props with type Object/Array must use a factory function ' +
          'to return the default value.',
          vm
        )
      }
    // ...
    return typeof def === 'function' && getType(prop.type) !== 'Function'
        ? def.call(vm)
        : def
}

那么,就提出了一个疑问,Vue的props中的数组和对象的default为什么要用工厂函数来返回?

解答

有的文章说是,为了不影响父组件,但是,感觉解释不了这个问题。

后来,我觉得是因为,这一个组件,会多次实例化调用(一个组件,可能在一个页面里调用多次), 如果不用工厂函数的话,那么vm1修改了default属性值,那么vm2也会变化的,这就跟我们的初衷不符合了,所以为了不互相影响,必须使用工厂函数来创建新的引用内存。