Skip to content

15 - 合并配置 - part 1 #15

@chenfaxiang

Description

@chenfaxiang

合并配置

前面在 new Vue 的过程中通常有两种情况,一种是外部代码主动调用 new Vue(options) 的方式实例化一个 Vue 对象;另一种是上一节接触到的在内部通过 new Vue(options) 实例化一个子组件。然而,无论哪一种情况都会执行实例的 _init(options) 方法,首先会执行一个 merge options 的逻辑,代码在 /core/instance/init.js 中如下:

Vue.prototype._init = function (options?: Object) {
    //其它代码
    // a flag to avoid this being observed
    vm._isVue = true
    // merge options —— 合并配置
    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.constructor),
        options || {},
        vm
      )
    }
    // 其它代码
}

通过 if else 就能看出在不同场景下 options 的合并逻辑是不一样的,并且传入的 options 值也不太一样。下面对两种情况分别学习一波,实际例子:

import Vue from 'vue'

let childComp = {
  template: '<div>{{msg}}</div>',
  created() {
    console.log('child created')
  },
  mounted() {
    console.log('child mounted')
  },
  data() {
    return {
      msg: 'Hello Vue'
    }
  }
}

Vue.mixin({
  created() {
    console.log('parent created')
  }
})

let app = new Vue({
  el: '#app',
  render: h => h(childComp)
})

外部调用场景

当执行 new Vue 的时候,在执行 this._init(options) 的时候,就会执行如下逻辑去合并 options

vm.$options = mergeOptions(
  resolveConstructorOptions(vm.constructor),
  options || {},
  vm
)

这里通过调用 mergeOptions 方法来合并,它实际上就是把 resolveConstructorOptions(vm.constructor) 的返回值和 options 做合并;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions