返回

从实例挂载学习 Vue 源码

前端

前言

学习 Vue 源码之前,我们需要先了解源码目录设计(了解各个模块的功能)和 Flow 语法。Flow 语法可以参照 v-model 源码学习中提到的 flow 语法介绍,也可以到官网了解更多。

实例挂载

通过源码我们可以看到,实例挂载实际上就是一个构造函数。我们往后看这里有很多 xxxMixin 的函数调用,并把它们都当作参数传给了 initMixin 函数。

export function initMixin(Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
    const vm: Component = this
    // a lot of other stuff here...
  }
}

接下来,我们看看 _init 函数做了些什么。

export function _init(this: Component, options?: Object) {
  const vm: Component = this
  // flow 中的 this 类型标注了以后,就可以用它的属性了
  vm.$options = options
  // 初始化各种实例属性
  // ...

  // 观测 data
  if (vm.$options.data) {
    _initData(vm)
  }
  // 观测 props
  if (vm.$options.props) {
    _initProps(vm)
  }
  // 观测 methods
  if (vm.$options.methods) {
    _initMethods(vm)
  }
  // 观测 computed
  if (vm.$options.computed) {
    _initComputed(vm)
  }
  // 观测 watch
  if (vm.$options.watch) {
    _initWatch(vm)
  }
  // ...

  // 渲染挂载
  if (vm.$options.el) {
    vm.$mount(vm.$options.el)
  }
}

在 _init 函数中,我们首先初始化了各种实例属性,然后观测了 data、props、methods、computed 和 watch。最后,如果提供了 el 选项,则会调用 $mount 方法进行渲染挂载。

总结

从实例挂载的代码中,我们可以看到 Vue 实例是如何被创建和初始化的。我们还看到了 Vue 实例的各种属性是如何被观测的。这些知识对于理解 Vue 的运行机制非常重要。