从入口代码开始分析,我们先来分析 new Vue 背后发生了哪些事情。我们都知道,new 关键字在 Javascript 语言中代表实例化是一个对象,而 Vue 实际上是一个类,类在 Javascript 中是用 Function 来实现的,来看一下源码,在src/core/instance/index.js 中。
//vue 构造函数
function Vue (options) {
console.log(4);
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 只能通过 new 关键字初始化,然后会调用 this._init 方法, 该方法在 src/core/instance/init.js 中定义。
Vue.prototype._init = function (options?: Object) {//初始化函数
// debugger
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),//解析constructor上的options属性的
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
//初始化 代理 监听
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self 暴露真实的self
vm._self = vm
console.log(2);
initLifecycle(vm)//初始化生命周期 标志
initEvents(vm)//初始化事件
initRender(vm)// 初始化渲染
callHook(vm, 'beforeCreate')//触发beforeCreate钩子函数
initInjections(vm) // resolve injections before data/props在数据/道具之前解决注入问题 //初始化 inject
initState(vm)//初始化状态
initProvide(vm) // resolve provide after data/props解决后提供数据/道具 provide 选项应该是一个对象或返回一个对象的函数。该对象包含可注入其子孙的属性,用于组件之间通信。
callHook(vm, 'created')//触发created钩子函数
console.log(vm);
/* 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) {
// Vue 的$mount()为手动挂载,
// 在项目中可用于延时挂载(例如在挂载之前要进行一些其他操作、判断等),之后要手动挂载上。
// new Vue时,el和$mount并没有本质上的不同。
vm.$mount(vm.$options.el)
}
}
Vue 初始化主要就干了几件事情,合并配置,初始化生命周期,初始化事件中心,初始化渲染,初始化 data、props、computed、watcher 等等。