Vue构造函数
我们知道core/instance目录主要是用来实例化Vue对象,所以我们在这个目录下去寻找Vue构造函数。果然找到了Vue构造函数的定义。
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)
}
当你新建一个Vue实例时候,会判断如果当前的环境不是生产环境,且你在调用Vue的时候,没有用new操作符。就会调用warn函数,抛出一个警告。告诉你Vue是一个构造函数,需要用new操作符去调用。这个warn函数不是单纯的console.warn,它的实现我们后面的博文会介绍。
接下来,把options作为参数调用_init方法。options不做过多的介绍了,就是你调用new Vue时候传入的参数。在深入_init方法之前,我们先把目光移到index.js文件里
function Vue (options) {
...
}
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
在Vue的构造函数定义之后,有一系列方法会被调用,这些方法主要用来给Vue函数添加一些原型属性和方法的。其中就有接下来要介绍的Vue.prototyoe._init
Vue.prototype._init
在core/instance/init.js中我们找到了_init的定义。
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
// 有子组件时,options._isComponent才会为true
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')
initState(vm)
initProvide(vm)
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)
}
}
我们逐一来分析上述代码。首先缓存当前的上下文到vm变量中,方便之后调用。然后设置_uid属性。_uid属性是唯一的。当触发init方法,新建Vue实例时(当渲染组件时也会触发)uid都会递增。
下面这段代码主要是用来测试代码性能的,在这个时候相当于打了一个"标记点"来测试性能。
let startTag, endTag
/* istanbul ignore if */
process.env.NODE_ENV === 'develop'
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
startTag = `vue-perf-start:${vm._uid}`
endTag = `vue-perf-end:${vm._uid}`
mark(startTag)
}