new Vue 发生了什么?

new Vue 发生了什么

new vue 我们从入口分析,我们new 一个实例化对象,是由Funcction实现的,来看一下源码,在src/core/instance/index.js 中。

import { initMixin } from './init'

import { stateMixin } from './state'

import { renderMixin } from './render'

import { eventsMixin } from './events'

import { lifecycleMixin } from './lifecycle'

import { warn } from '../util/index'

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)

}

initMixin(Vue)

stateMixin(Vue)

eventsMixin(Vue)

lifecycleMixin(Vue)

renderMixin(Vue)

由此可以看出 Function 里面 this._init(options), 通过原型的调用 在这里调用

src/core/instance/init.js

Vue.prototype._init = function (options?: Object) {

const vm: Component = this

// a uid

vm._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 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

)

}

/* istanbul ignore else */

if (process.env.NODE_ENV !== 'production') {

initProxy(vm)

} else {

vm._renderProxy = vm

}

// expose real self

vm._self = vm

initLifecycle(vm)

initEvents(vm)

initRender(vm)

callHook(vm, 'beforeCreate')

initInjections(vm) // resolve injections before data/props

initState(vm)

initProvide(vm) // resolve provide after data/props

callHook(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)

}

}

从中可以看下,初始化生命周期、初始化事件,初始化data/props/render/watch/computed等

从中可以看出 beforeCreate 在 初始化data前就开始的生命周期,创建data之后 created生命周期