淺析Vue原始碼(一)—— 造物創世
宣告:英文註解為尤雨溪大神原著,中文為本人理解翻譯。水平有限若理解有誤請以原著為準,望指正,見諒哈~
要是覺得還不錯,快給我個star,快點這裡 ofollow,noindex">github
Vue 專案的起源,其實是源於對Vue進行例項化:
new Vue({ el: ..., data: ..., .... }) 複製程式碼
那麼在這次例項化的過程中,究竟發生了哪些行為?讓我們來一探究竟。開啟Vue的原始碼檔案,其核心程式碼在src/core目錄下。下面我們從入口檔案index.js開始進入:
// 這個應該是例項化的引入 import Vue from './instance/index' //這個應該是初始化一些全域性API import { initGlobalAPI } from './global-api/index' // 這個應該是從判斷執行環境中的引入是否是ssr環境,是一個Boolea型別 import { isServerRendering } from 'core/util/env' // 這個應該是virtualDom編譯成renderContext的方法 import { FunctionalRenderContext } from 'core/vdom/create-functional-component' //這裡開始執行初始化全域性變數 initGlobalAPI(Vue) //為Vue原型定義屬性$isServer Object.defineProperty(Vue.prototype, '$isServer', { get: isServerRendering }) // 為Vue原型定義屬性$ssrContext Object.defineProperty(Vue.prototype, '$ssrContext', { get () { /* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext } }) // 為vue原型定義當為ssr環境執行時去載入FunctionalRenderContext方法 // expose FunctionalRenderContext for ssr runtime helper installation Object.defineProperty(Vue, 'FunctionalRenderContext', { value: FunctionalRenderContext }) Vue.version = '__VERSION__' // 匯出Vue export default Vue 複製程式碼
接下來我們來看一下各個載入檔案:
import Vue from './instance/index' 複製程式碼
內容如下:
import { initMixin } from './init' import { stateMixin } from './state' import { renderMixin } from './render' import { eventsMixin } from './events' import { lifecycleMixin } from './lifecycle' import { warn } from '../util/index' 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 複製程式碼
這裡簡單粗暴的定義了一個 Vue Class,然後又呼叫了一系列init、mixin這樣的方法來初始化一些功能,具體的我們後面在分析,不過通過程式碼我們可以確認的是:沒錯!這裡確實是匯出了一個 Vue 功能類。
import { initGlobalAPI } from './global-api/index' 複製程式碼
initGlobalAPI這個東西,其實在Vue官網上,就已經為我們說明了Vue的全域性屬性:

import config from '../config' import { initUse } from './use' import { initMixin } from './mixin' import { initExtend } from './extend' import { initAssetRegisters } from './assets' import { set, del } from '../observer/index' import { ASSET_TYPES } from 'shared/constants' import builtInComponents from '../components/index' import { warn, extend, nextTick, mergeOptions, defineReactive } from '../util/index' export function initGlobalAPI (Vue: GlobalAPI) { // config const configDef = {} configDef.get = () => config if (process.env.NODE_ENV !== 'production') { configDef.set = () => { warn( 'Do not replace the Vue.config object, set individual fields instead.' ) } } Object.defineProperty(Vue, 'config', configDef) // 這些工具方法不視作全域性API的一部分,除非你已經意識到某些風險,否則不要去依賴他們 // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on // them unless you are aware of the risk. Vue.util = { warn, extend, mergeOptions, defineReactive } // 這裡定義全域性屬性 Vue.set = set Vue.delete = del Vue.nextTick = nextTick Vue.options = Object.create(null) ASSET_TYPES.forEach(type => { Vue.options[type + 's'] = Object.create(null) }) // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue extend(Vue.options.components, builtInComponents) // 定義全域性方法 initUse(Vue) initMixin(Vue) initExtend(Vue) initAssetRegisters(Vue) } 複製程式碼
♦【Vue.config】 各種全域性配置項
♦【Vue.util】 各種工具函式,還有一些相容性的標誌位(哇,不用自己判斷瀏覽器了,Vue已經判斷好了) ♦【Vue.set/delete】 這個你文件應該見過
♦【Vue.nextTick】 這個是下一次更新前合併處理data變化做的一次優化
♦【Vue.options】 這個options和我們上面用來構造例項的options不一樣。這個是Vue預設提供的資源(元件指令過濾器)。
♦【Vue.use】 通過initUse方法定義
♦【Vue.mixin】 通過initMixin方法定義
♦【Vue.extend】通過initExtend方法定義
import { isServerRendering } from 'core/util/env' 複製程式碼
// 這個需要用懶載入在vue渲染前 // this needs to be lazy-evaled because vue may be required before // ssr使用的時候要把VUE_ENV(vue環境)設定成'server' // vue-server-renderer can set VUE_ENV let _isServer export const isServerRendering = () => { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && !inWeex && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'].env.VUE_ENV === 'server' } else { _isServer = false } } return _isServer } 複製程式碼
import { FunctionalRenderContext } from 'core/vdom/create-functional-component' 複製程式碼
export function FunctionalRenderContext ( data: VNodeData, props: Object, children: ?Array<VNode>, parent: Component, Ctor: Class<Component> ) { const options = Ctor.options // 確保createElement方法在components方法中 // ensure the createElement function in functional components // 得到一個唯一的context上下文-主要是為了檢查是否有重複命名確保唯一性 // gets a unique context - this is necessary for correct named slot check let contextVm if (hasOwn(parent, '_uid')) { // 表示不存在建立 contextVm = Object.create(parent) // $flow-disable-line contextVm._original = parent } else { // the context vm passed in is a functional context as well. // in this case we want to make sure we are able to get a hold to the // real context instance. contextVm = parent // $flow-disable-line parent = parent._original } const isCompiled = isTrue(options._compiled) const needNormalization = !isCompiled this.data = data this.props = props this.children = children this.parent = parent this.listeners = data.on || emptyObject this.injections = resolveInject(options.inject, parent) this.slots = () => resolveSlots(children, parent) // 支援把template編譯的方法 // support for compiled functional template if (isCompiled) { // exposing $options for renderStatic() this.$options = options // pre-resolve slots for renderSlot() this.$slots = this.slots() this.$scopedSlots = data.scopedSlots || emptyObject } if (options._scopeId) { this._c = (a, b, c, d) => { const vnode = createElement(contextVm, a, b, c, d, needNormalization) if (vnode && !Array.isArray(vnode)) { vnode.fnScopeId = options._scopeId vnode.fnContext = parent } return vnode } } else { this._c = (a, b, c, d) => createElement(contextVm, a, b, c, d, needNormalization) } } installRenderHelpers(FunctionalRenderContext.prototype) 複製程式碼
到這裡,我們的入口檔案差不多就瞭解清楚了,接下來,我們開始去了解一下 Vue class 的具體實現,其中我們會了解到Vue的相關生命週期的知識。