Vue源码笔记 — 数据驱动--new Vue 发生了什么
文章目录
Vue版本:2.5.17-beta.0
当 new Vue(options) 时调用的是 src/core/instance/index.js 文件中的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)
}
可以看到在初始化后又调用了 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)
}
}
上面源码大体分为了三个大步骤:
-
options为 new Vue(options) 时传入的选项,并通过mergeOptions方法把 options 合并到vm.$options中。 - 调用
initLifecycle(vm)、initEvents(vm)、initRender(vm)、initState(vm)函数进行生命周期的初始化、事件中心的初始化、渲染的初始化、data props computed watcher的初始化等等。 - 调用
vm.$mount(vm.$options.el)进行挂载渲染成真实dom。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论