Vue源码中的选项合并,针对 内部组件实例化 和 根组件实例化 的不同处理方式的不理解?

作者站长头像
站长
· 阅读数 21
// Vue 2.0.0 src/core/instance/init.js
export function initMixin(Vue: Class<Component>) {
    Vue.prototype._init = function (options?: Object) {
        if (options && options._isComponent) {
            // optimize internal component instantiation
            // since dynamic options merging is pretty slow, and none of the
            // internal component options needs special treatment.
            initInternalComponent(vm, options)
        }
        else {
            vm.$options = mergeOptions(
                resolveConstructorOptions(vm),
                options || {},
                vm
            )
        }

注释中说,动态选项合并很慢,而且内部组件的选项不需要特殊对待,所以使用了initInternalComponent简单处理下,有2个问题

(1)内部组件的选项不需要特殊对待,为何?

(2)动态选项合并很慢,应该是指mergeOptions的操作很耗时,看了下里边的逻辑,并没有觉得哪里很耗时?

回复
1个回答
avatar
test
2024-07-03
  1. 因为已经确定了 options(代码是作者自己写的,自己当然清楚),不需要再合并计算。mergeOptions 是为了 mixin、extend 这类不确定的、灵活性较高的场景,内部组件里没这需要,所以跳过就好了。
  2. 主要是有递归,递归在几乎所有编程语言中从来都是开销比较大的一种调用方式,能省则省。
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容