主要是记录自己在学习 Vue 源码时的心得,学习的版本是2.5.17-beta.0. 主要参考的博客是liutao/vue2.0-source。
入口
entry-runtime-with-compiler
跟随npm run dev,可以看到最终的入口文件是src/platforms/web/entry-runtime-with-compiler.js,Vue 函数的定义是从./runtime/index.js中导入的。这个文件主要是
- 修改了
Vue.prototype.$mount的定义 - 添加了
Vue.compile
runtime/index
再看看runtime/index中干了什么:
1 | Vue.config.mustUseProp = mustUseProp |
- 从
src/core/index.js导入 Vue - 为
Vue.config添加了一系列平台相关工具函数 - 扩展了
Vue.options.directives(v-model和v-show)和Vue.options.components(Transition和TransitionGroup) - 在
Vue.prototype上添加了__patch__(虚拟 dom 相关)和$mount(挂载元素)
core/index
在core/index中其实也没有什么,主要就是
1 | import Vue from './instance/index'; |
instance/index
最后终于到了instance/index,这里终于可以看到Vue的构造函数定义了~~~~
1 | function Vue(options) { |
可以看到主要就是调用了一个_init方法,从这个函数追溯可以了解到整个 Vue 的生命周期,之后单独详细说明。
下面的其他几个方法主要就是给Vue.prototype挂载各种实例方法,这里先简单挨个描述
stateMixin: 挂载了$data、$props、$set、$delete、$watcheventsMixin:挂载了$on、$once、$off、$emitlifecycleMixin: 挂载了_update、$forceUpdate、$destroyrenderMixin: 挂载了$nextTick、_render以及一系列在render帮助函数,如下1
2
3
4
5
6
7
8
9
10
11
12
13
14
15target._o = markOnce
target._n = toNumber
target._s = toString
target._l = renderList
target._t = renderSlot
target._q = looseEqual
target._i = looseIndexOf
target._m = renderStatic
target._f = resolveFilter
target._k = checkKeyCodes
target._b = bindObjectProps
target._v = createTextVNode
target._e = createEmptyVNode
target._u = resolveScopedSlots
target._g = bindObjectListeners
至此,我们就知道了整个Vue框架的入口了,从入口出发就可以了解到整个 Vue 的方方面面,后续挨个记录。