从入口代码开始分析,我们先来分析 new Vue 背后发生了哪些事情。我们都知道,new 关键字在 Javascript 语言中代表实例化是一个对象,而 Vue 实际上是一个类,类在 Javascript 中是用 Function 来实现的,来看一下源码,在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)
}

可以看到 Vue 只能通过 new 关键字初始化,然后会调用 this._init 方法, 该方法在 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)
}
}

Vue 初始化主要就干了几件事情,合并配置,初始化生命周期,初始化事件中心,初始化渲染,初始化 data、props、computed、watcher 等等。

总结

Vue 的初始化逻辑写的非常清楚,把不同的功能逻辑拆成一些单独的函数执行,让主线逻辑一目了然,这样的编程思想是非常值得借鉴和学习的。

-----------------转自慕课网vue源码解析视频教程的内容-----------------

最新文章

  1. <程序员从入门到精通> -- How
  2. 从is(":checked")说起
  3. Web前端工程师
  4. 使用afinal下载文件并且在状态栏中显示下载的进度
  5. view类的setVisibility
  6. 网络模拟器WANem使用配置图文教程
  7. js __proto 和prototype
  8. SPFA算法学习笔记
  9. 38. Same Tree && Symmetric Tree
  10. Intent的简介以及属性详解
  11. SSH配置log4j的方法
  12. C# 里窗体里(windows form)怎么播放音乐
  13. 【C#编程基础学习笔记】4---Convert类型转换
  14. cf C. Secrets
  15. HDU 1548 A strange lift(Dijkstra,简单BFS)
  16. SQL SERVER 2008 Hierarchyid数据类型
  17. php从气象局获取天气预报并保存到服务器
  18. iptables中DNAT的配置方法
  19. 【转】shell脚本实现多台服务器自动巡检--可参考学习
  20. 【OpenGL】代码记录01创建窗口

热门文章

  1. Ream--(objc)写事务精简方案
  2. MySQL必知必会--汇 总 数 据
  3. Linux报错:rm: cannot remove 'xxx': Is a directory
  4. Winfrom中From控件的重绘
  5. neo4j学习摘要
  6. idea 编译报错 Build completed with 1 error and 0 warnings in 2 s 113 ms
  7. 为什么我用Ipad Pro做电子笔记和看PDF电子书
  8. 《茶余饭后小故事》MV*、MVC、MVP、MVVM的前世今生
  9. Auto-Encoder(自编码器)原理
  10. 一些实用的GitHub项目