最近一直忙於找實習,一直奔波於北京和學校兩地之間,很榮幸能加入一家小公司,因爲以前一直使用的React,如今的公司用VUE,因此花費了兩天時間學習了VUE的基本使用,這兩天心血來潮準備看看VUE的源碼,我只是一個大二的初生牛犢,有錯誤的地方還望你們指出來,咱們共同窗習。喜歡的請點贊html
今天開始,我準備淺談一下本身對於VUE源碼的理解,同時配套源碼的註釋,具體地址過兩天將會發布 ,同時文章裏面所用到的代碼都會有一個單獨的文章進行彙總 ,今天先說說Vue這個 構造函數vue
使用VUE的時候咱們須要new一下,故追本尋源,在 ./instance/index
文件中找到定義VUE構造函數的代碼node
// 從五個文件導入五個方法(不包括 warn)
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'
// 定義 Vue 構造函數
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 做爲參數傳遞給導入的五個方法
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
// 導出 Vue
export default Vue
複製代碼
能夠看出使用率安全模式提醒你使用new操做符來調用VUE,接着將VUE做爲參數,傳遞給了五個引入的方法,最後導出VUE。ios
那麼這五個方法又作了什麼?git
initMixin
export function initMixin (Vue: Class<Component>) {
Vue.prototype._init = function (options?: Object) {
// ... _init 方法的函數體,此處省略
}
}
複製代碼
原來是在VUE的原型上添加了_init
方法,這個方法應該是內部初始化的一個方法,在上面咱們看到過這個方法。github
也就是說當咱們調用new VUE()
的時候會執行this._init(options)
web
stateMixin
const dataDef = {}
dataDef.get = function () { return this._data }
const propsDef = {}
propsDef.get = function () { return this._props }
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData: Object) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
)
}
propsDef.set = function () {
warn(`$props is readonly.`, this)
}
}
Object.defineProperty(Vue.prototype, '$data', dataDef)
Object.defineProperty(Vue.prototype, '$props', propsDef)
複製代碼
最後面兩句很熟悉,使用Object.definePropety
在Vue.prototype
上定義了兩個屬性,分別是$data
和$props
,這兩個屬性的定義分別寫在了dataDef
和propsDef
這兩個對象上 ,仔細看上面的代碼,首先分別是get
,能夠能夠看到$data
屬性實際上代理的是_data
這個屬性,而$props
代理的是_props
這個實力屬性,而後有一個生產環境的判斷,若是不是生產環境的話,就爲$data
和$props
這兩個屬性設置了set,實際上就是想提醒一下你:別想修改我,也就是說$data
和$props
是兩個只讀的屬性。(又get到新的知識點,開心不😄)npm
接下來,stateMixin
又在Vue.prototype
上定義了三個方法api
Vue.prototype.$set = set
Vue.prototype.$delete = del
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {
// ...
}
複製代碼
分別是$set
,$delete
,$watch
,實際上你都見過這些東西數組
eventsMixin
Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component {}
Vue.prototype.$once = function (event: string, fn: Function): Component {}
Vue.prototype.$off = function (event?: string | Array<string>, fn?: Function): Component {}
Vue.prototype.$emit = function (event: string): Component {}
複製代碼
這個方法又在Vue.prototype
上添加了四個方法,如上
lifecycleMixin
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {}
Vue.prototype.$forceUpdate = function () {}
Vue.prototype.$destroy = function () {}
複製代碼
這個方法在Vue.prototype
上添加了三個方法,是否是感受很熟悉 ?
renderMixin
這個方法的一開始以Vue.prototype
爲參數調用了installRenderHelpers
函數,這個函數來自於與render.js
文件相同目錄下的render-helpers/index.js
文件,找到這個函數
export function installRenderHelpers (target: any) {
target._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.prototype
上添加一系列的方法
renderMixin
方法在執行完installRenderHelpers
函數以後,又在Vue.prototype
上添加了兩個方法,分別是$nextTick
和_render
,最終通過renderMixin
以後,Vue.prototype
又被添加了以下方法:
// installRenderHelpers 函數中
Vue.prototype._o = markOnce
Vue.prototype._n = toNumber
Vue.prototype._s = toString
Vue.prototype._l = renderList
Vue.prototype._t = renderSlot
Vue.prototype._q = looseEqual
Vue.prototype._i = looseIndexOf
Vue.prototype._m = renderStatic
Vue.prototype._f = resolveFilter
Vue.prototype._k = checkKeyCodes
Vue.prototype._b = bindObjectProps
Vue.prototype._v = createTextVNode
Vue.prototype._e = createEmptyVNode
Vue.prototype._u = resolveScopedSlots
Vue.prototype._g = bindObjectListeners
Vue.prototype.$nextTick = function (fn: Function) {}
Vue.prototype._render = function (): VNode {}
複製代碼
至此,instance/index.js
文件中的代碼就運行完畢了(具體指npm run dev
命令時構建的運行).大概瞭解了每一個 Mixin
方法的做用騎士就是包裝Vue.prototype
,在其上掛載一些屬性和方法,下面我會把代碼合併在一塊,以便於之後查看
依舊按照追本溯源的原則,咱們找到前一個文件core/index.js
,下面是其所有代碼 ,一樣高效簡短
// 從 Vue 的出生文件導入 Vue
import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
import { isServerRendering } from 'core/util/env'
import { FunctionalRenderContext } from 'core/vdom/create-functional-component'
// 將 Vue 構造函數做爲參數,傳遞給 initGlobalAPI 方法,該方法來自 ./global-api/index.js 文件
initGlobalAPI(Vue)
// 在 Vue.prototype 上添加 $isServer 屬性,該屬性代理了來自 core/util/env.js 文件的 isServerRendering 方法
Object.defineProperty(Vue.prototype, '$isServer', {
get: isServerRendering
})
// 在 Vue.prototype 上添加 $ssrContext 屬性
Object.defineProperty(Vue.prototype, '$ssrContext', {
get () {
/* istanbul ignore next */
return this.$vnode && this.$vnode.ssrContext
}
})
// expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
value: FunctionalRenderContext
})
// Vue.version 存儲了當前 Vue 的版本號
Vue.version = '__VERSION__'
// 導出 Vue
export default Vue
複製代碼
上面的代碼中,首先從Vue
的出生文件,也就是instance/index.js
文件導入Vue
,而後分別從三個文件導入了三個變量 ,
其中initGlobalAPI
是一個函數,而且以Vue
構造函數做爲參數進行調用
initGlobalAPI(Vue)
而後在Vue.prototype
上分別添加了兩個只讀的屬性,分別是:$isServer
和$ssrContext
。接着在Vue
構造函數上定義了FunctionalRenderContext
靜態屬性,而且FunctionalRenderContext
屬性的值來自於core/vdom/create-functional-component
文件,從命名來看,這個屬性是爲了在SSR中使用它。
最後,在Vue
構造函數上添加了一個靜態屬性version
,存儲了當前Vue
的版本值,可是這裏的'_VERSION'
是什麼東西呢?找了半天打開scripts.config.js
文件,找到了getConfig
方法,其中有這麼一句話:_VERSION_:version
。也就是說最後的_VERSION_
最終將被version
的值替換,而version
的值就是Vu
的版本號
回頭繼續看看 initGlobalAPI(Vue)
這段代碼,貌似是要給Vue
上添加一些全局的API
,實際上就是這樣的,這些全局API
以靜態屬性和方法的形式被添加到Vue
構造函數上,找到這個方法,看看主要作了什麼
// 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)
複製代碼
首先是這樣 一段代碼,意思是給vue···添加一個
config```屬性,也是一個只讀屬性,你修改它會在非生產模式下給你一個友好的提示。
那麼Vue.config
的值是什麼呢?在src/core/global-api/index/js
文件開頭有這樣一行代碼
import config from '../config'
因此是從這個文件導出的對象。
接着是下面這段代碼
// 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
中添加了util
屬性,這是一個對象,這個對象擁有四個屬性分別是: warn
,extend
,ergeOptions
以及defineReactive
,這四個屬性來自於core/util/index.js
文件 大概意思就是Vue.util
以及util
下的四個方法都是不被公認是公共API的一部分,要避免依賴他們,可是你依然能夠用,不過你仍是不要用的好
而後是這樣一段代碼
Vue.set = set
Vue.delete = del
Vue.nextTick = nextTick
複製代碼
接着給Vue
添加了三個屬性
// 2.6 explicit observable API
Vue.observable = <T>(obj: T): T => {
observe(obj)
return obj
}
複製代碼
這段代碼給Vue
添加了observable
方法,這個方法先是調用了observe
這個方法,而後返回了obj
(傳入的參數)
上面的註釋說明這個API是添加Vue
2.6,接着是下面的代碼
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) 複製代碼
這段代碼先是經過object.create()
建立了一個新的空對象,添加到Vue
的options
屬性上,接着給options
屬性添加了值(ASSET_TYPES
是一個數組),這段代碼執行完其實就是這樣
Vue.options = {
components: Object.create(null),
directives: Object.create(null),
filters: Object.create(null),
_base: Vue
}
複製代碼
接着就是將builtInComponents
的屬性混合到Vue.options.components
中
最終Vue.options.components
的值以下:
Vue.options.components = {
KeepAlive
}
複製代碼
那麼到如今爲止,Vue.options
已經變成了這個亞子
Vue.options = {
components: {
KeepAlive
},
directives: Object.create(null),
filters: Object.create(null),
_base: Vue
}
複製代碼
咱們繼續看代碼
initUse(Vue)
initMixin(Vue)
initExtend(Vue)
initAssetRegisters(Vue)
複製代碼
這四個方法來自於四個文件 ,咱們分別來看看
initUse
/* @flow */
import { toArray } from '../util/index'
export function initUse (Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) {
// ...
}
}
複製代碼
其實很簡單,就是在Vue
函數上添加use
方法,也就是咱們常常在main.js
文件中用的全局API,用來安裝VUE
插件。
initMixin
/* @flow */
import { mergeOptions } from '../util/index'
export function initMixin (Vue: GlobalAPI) {
Vue.mixin = function (mixin: Object) {
this.options = mergeOptions(this.options, mixin)
return this
}
}
複製代碼
這段代碼就是在Vue
中添加mixin
這個全局API
initExtend
export function initExtend (Vue: GlobalAPI) {
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0
let cid = 1
/**
* Class inheritance
*/
Vue.extend = function (extendOptions: Object): Function {
// ...
}
}
複製代碼
initExtend
方法在Vue
中添加了Vue.cid
靜態屬性,和Vue.extend
靜態方法
initAssetRegisters
export function initAssetRegisters (Vue: GlobalAPI) {
/**
* Create asset registration methods.
*/
ASSET_TYPES.forEach(type => {
Vue[type] = function (
id: string,
definition: Function | Object
): Function | Object | void {
// ......
}
})
}
複製代碼
其中某個東西咱們以前見過了 ,因此最終initAssetRegisters
方法,Vue
又多了三個靜態方法
Vue.component
Vue.directive
Vue.filter
複製代碼
這三個方法你們確定不陌生,分別用來全局註冊組件,指令和過濾器。
這樣 咱們大概瞭解了上述幾個文件的做用
如今,咱們弄清了Vue
構造函數的過程當中的兩個主要的文件,分別是:core/instance/index.js
,core/index.js
文件,咱們知道core
目錄下的文件存放的是與平臺無關的代碼,可是,Vue
是一個Multi-platform
的項目,不一樣平臺可能會內置不一樣的組件,指令或者一些平臺特有的功能等,那麼就須要根據不一樣的平臺進行平臺化地包裝。
咱們打開platforms
目錄,能夠發現有兩個子目錄web
和weex
。這兩個子目錄的做用就是分別爲相應的平臺對核心的Vue
進行包裝的。咱們先去看看web
的根文件
/* @flow */
import Vue from 'core/index'
import config from 'core/config'
import { extend, noop } from 'shared/util'
import { mountComponent } from 'core/instance/lifecycle'
import { devtools, inBrowser } from 'core/util/index'
import {
query,
mustUseProp,
isReservedTag,
isReservedAttr,
getTagNamespace,
isUnknownElement
} from 'web/util/index'
import { patch } from './patch'
import platformDirectives from './directives/index'
import platformComponents from './components/index'
// install platform specific utils
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement
複製代碼
首先依舊是導入了不少文件,而後對core/config.js
文件進行一些修改吧(本來文件裏的對象大部分屬性都是初始化了一個初始值),註釋的意思是這個配置是與平臺有關的,極可能會被覆蓋掉,這個時候咱們回來再看看代碼,其實就是在覆蓋默認導出的config
對象的屬性,至於這些東西的做用,暫時還不知道
接着是下面兩句代碼
/ install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)
複製代碼
安裝特定平臺運行時的指令和組件,以前咱們已經看到過Vue.options
是什麼樣的,通過這樣一番折騰,變成啥了?
咱們先看看platformDirectives
和platformComponents
長什麼樣,順着導入的文件地址,咱們看到platformDirectives
實際是這樣
platformDirectives = {
model,
show
}
複製代碼
也就是通過 extend(Vue.options.directives, platformDirectives)
以後,Vue.options
將變成:
Vue.options = {
components: {
KeepAlive
},
directives: {
model,
show
},
filters: Object.create(null),
_base: Vue
}
複製代碼
一樣的道理,變化以後是下面這樣的
Vue.options = {
components: {
KeepAlive,
Transition,
TransitionGroup
},
directives: {
model,
show
},
filters: Object.create(null),
_base: Vue
}
複製代碼
如今咱們搞清楚了做用,就是Vue.options
上添加web
平臺運行時特定的指令和組件。
接着往下看看
// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop
// public mount method
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
複製代碼
首先在Vue.prototype
上添加了_patch_
方法,若是瀏覽器環境運行的話這個方法的值爲patch
函數,不然是一個空函數noop
,而後又在Vue.prototype
上添加了$mount
方法,暫時不須要關注方法的做用和內容吧。
再往下的一段代碼
if (inBrowser) {
setTimeout(() => {
if (config.devtools) {
if (devtools) {
devtools.emit('init', Vue)
} else if (
process.env.NODE_ENV !== 'production' &&
process.env.NODE_ENV !== 'test'
) {
console[console.info ? 'info' : 'log'](
'Download the Vue Devtools extension for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools'
)
}
}
if (process.env.NODE_ENV !== 'production' &&
process.env.NODE_ENV !== 'test' &&
config.productionTip !== false &&
typeof console !== 'undefined'
) {
console[console.info ? 'info' : 'log'](
`You are running Vue in development mode.\n` +
`Make sure to turn on production mode when deploying for production.\n` +
`See more tips at https://vuejs.org/guide/deployment.html`
)
}
}, 0)
}
export default Vue
複製代碼
這段代碼是vue-tools
的全局鉤子,它被包裹在setTimeout
中,最後導出了Vue
在看完上面這個文件以後,其實運行
時版本的Vue
構造函數已經"成型",咱們看到entry-runtime.js
文件只有兩行代碼,
import Vue from './runtime/index'
export default Vue
複製代碼
能夠發現,運行時
版的入口文件,導出的Vue
就在./runtime/index.js
爲止。而後咱們須要瞭解完整的Vue
,入口文件是entry-runtime-with-compiler.js
,因此完整版和運行版差異就在compiler,因此咱們要看的這個文件做用就是在運行時版本的基礎上添加compiler
,先看看文件的代碼
/* @flow */
import config from 'core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'
import Vue from './runtime/index'
import { query } from './util/index'
import { compileToFunctions } from './compiler/index'
import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'
const idToTemplate = cached(id => {
const el = query(id)
return el && el.innerHTML
})
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
return this
}
const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
const { render, staticRenderFns } = compileToFunctions(template, {
outputSourceRange: process.env.NODE_ENV !== 'production',
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
return mount.call(this, el, hydrating)
}
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el: Element): string {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div')
container.appendChild(el.cloneNode(true))
return container.innerHTML
}
}
Vue.compile = compileToFunctions
export default Vue
複製代碼
看的出來先是導出了不少文件以及運行時的Vue,還從./compiler/index.js
文件中導入compileToFunctions
,後邊根據id獲取元素的innerHTML
,接着使用mount
變量緩存了Vue.prototype.$mount
方法,而後重寫了Vue.prototype.$mount
方法,後續接着獲取元素的outerHTML
,最終在Vue
上添加了一個全局的API:compileToFunctions
,導出了Vue
。
看完是否是有點懵逼?這個文件運行下來對Vue的影響有兩個,第一個影響是它重寫了Vue.prototype.$mount
方法;第二個是添加了Vue.compile
全局API,至於具體作什麼,咱們一步一步看!
首先,它待遇el
作了限制,Vue不能掛載在body
,html
這樣的根節點上,接下來的是很關鍵的邏輯:若是沒有定義redner
方法,則會把el
或者template
字符串轉換成render
方法。剛學習Vue不瞭解之前什麼狀況,在Vue2.0版本上,全部的Vue的組件的渲染最終都須要render
方法,不管咱們是用單文件的.vue
文件仍是寫了el
或者template
屬性,最終都會轉換成render
方法,這個過程是一個"在線編譯"的過程,它是調用compileToFunctions
方法實現的,這個後續介紹。最後,調用原先原型上的$mount
方法掛載。