Vue 源碼目錄 src
compiler: 編譯相關
core: 核心代碼
platforms: 不同平臺支持 web,weex
server: 服務端渲染
sfc: .vue 文件解析
shared: 共享代碼,遊覽器端和服務端都會用到的工具方法
Vue 對象
Vue 實際上是一個函數對象,定義在 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)
}
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
export default Vue
必須通過 new 創建
這裏的各種 xxMixin
函數通過擴展原型的方式增加 Vue 對象的功能, 比如 initMixin
:
Vue.prototype._init = function (options?: Object) { ......
_render 虛擬 Node 創建
定義在 src/core/instance/render.js
中
通過 vm._render
方法執行 createElement
創建 vm.vnode
createElement()
定義在 src/core/vdom/create-elemenet.js
Virtual DOM
虛擬 DOM: 使用一個原生 JS 對象去表述DOM節點,容易修改。對應的類:VNode src/core/vdom/vnode.js
借鑑了開源庫 snabbdom
VNode 裏面只用來映射到真實 DOM,沒有包含操作DOM的方法。
真正的 DOM 元素內容很多,直接操作修改性能差,所以引入 虛擬DOM。
在VNode修改後 Vue 通過 diff算法獲取修改前後的差異更新 真實DOM.
創建 VNode 後執行 vm._update,vm.__patch__
把 VNode 轉化成真實 DOM。