从new Vue可以看出,Vue是一个类,new Vue表示实例化这个类,那么这个类定义在哪里呢,观察源码可以看到定义的路径在
src/core/instance/index.js
function Vue (options) {if (process.env.NODE_ENV !== 'production' &&!(this instanceof Vue)) {warn('Vue is a constructor and should be called with the `new` keyword')}this._init(options)}
根据以上可以看出,new Vue的时候传入配置项开始初始化,调用了_init方法,该方法是挂载在Vue实例上的,源码路径
src/core/instance/index.js
export function initMixin (Vue: Class<Component>) {Vue.prototype._init = function (options?: Object) {const vm: Component = this// a uidvm._uid = uid++let startTag, endTag/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {startTag = `vue-perf-start:${vm._uid}`endTag = `vue-perf-end:${vm._uid}`mark(startTag)}// a flag to avoid this being observedvm._isVue = true// merge optionsif (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)}/* istanbul ignore else */if (process.env.NODE_ENV !== 'production') {initProxy(vm)} else {vm._renderProxy = vm}// expose real selfvm._self = vminitLifecycle(vm)initEvents(vm)initRender(vm)callHook(vm, 'beforeCreate')initInjections(vm) // resolve injections before data/propsinitState(vm)initProvide(vm) // resolve provide after data/propscallHook(vm, 'created')/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {vm._name = formatComponentName(vm, false)mark(endTag)measure(`vue ${vm._name} init`, startTag, endTag)}if (vm.$options.el) {vm.$mount(vm.$options.el)}}}
从上面的这个_init函数可以看出,初始化主要做了以下几件事
- 合并配置(options的合并)
- 初始化生命周期
- 初始化事件
- 初始化渲染
- 初始化 data,props,computed,watcher
下面我们来分析这段代码
if (vm.$options.el) {vm.$mount(vm.$options.el)}
在上述_init函数的最后,检测是否有el属性,有的话就执行vm.$mount方法挂载vm,把模版渲染为真实的DOM。
