Vue2 源碼漫游(一)
描述:
Vue框架中的基本原理可能大家都基本了解了,但是還沒有漫游一下源碼。
所以,覺得還是有必要跑一下。
由于是代碼漫游,所以大部分為關鍵性代碼,以主線路和主要分支的代碼為主,大部分理解都寫在代碼注釋中。
一、代碼主線
文件結構1-->4,代碼執行順序4-->1
1.platforms/web/entry-runtime.js/index.js
web不同平臺入口;
/* @flow */import Vue from './runtime/index'export default Vue
2.runtime/index.js
為Vue配置一些屬性方法
/* @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, isChrome } 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// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)// 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) : undefinedreturn mountComponent(this, el, hydrating)
}// devtools global hook
/* istanbul ignore next */
Vue.nextTick(() => {if (config.devtools) {if (devtools) {devtools.emit('init', Vue)} else if (process.env.NODE_ENV !== 'production' && isChrome) {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' &&config.productionTip !== false &&inBrowser && 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
3.core/index.js
/* @flow */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,創建了一個configDef對象,最終目的是為了Object.defineProperty(Vue, 'config', configDef)const configDef = {}configDef.get = () => configif (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.congfig的具體內容就要看../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.// 添加一些方法,但是該方法并不是公共API的一部分。源碼中引入了flow.jsVue.util = {warn, // 查看'../util/debug'extend,//查看'../sharde/util'mergeOptions,//查看'../util/options'defineReactive//查看'../observe/index'}Vue.set = set //查看'../observe/index' Vue.delete = del//查看'../observe/index'Vue.nextTick = nextTick//查看'../util/next-click'.在callbacks中注冊回調函數// 創建一個純凈的options對象,添加components、directives、filters屬性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// ../components/keep-alive.js 拷貝組件對象。該部分最重要的一部分。extend(Vue.options.components, builtInComponents)// Vue.options = {// components : {// KeepAlive : {// name : 'keep-alive',// abstract : true,// created : function created(){},// destoryed : function destoryed(){},// props : {// exclude : [String, RegExp, Array],// includen : [String, RegExp, Array],// max : [String, Number]// },// render : function render(){},// watch : {// exclude : function exclude(){},// includen : function includen(){},// }// },// directives : {},// filters : {},// _base : Vue// }// }// 添加Vue.use方法,使用插件,內部維護一個插件列表_installedPlugins,如果插件有install方法就執行自己的install方法,否則如果plugin是一個function就執行這個方法,傳參(this, args)initUse(Vue)// ./mixin.js 添加Vue.mixin方法,this.options = mergeOptions(this.options, mixin),initMixin(Vue)// ./extend.js 添加Vue.cid(每一個夠著函數實例都有一個cid,方便緩存),Vue.extend(options)方法initExtend(Vue)// ./assets.js 創建收集方法Vue[type] = function (id: string, definition: Function | Object),其中type : component / directive / filterinitAssetRegisters(Vue)
}
Vue.util對象的部分解釋:
Vue.util.warn
warn(msg, vm) 警告方法代碼在util/debug.js,
通過var trac = generateComponentTrace(vm)方法vm=vm.$parent遞歸收集到msg出處。
然后判斷是否存在console對象,如果有 console.error([Vue warn]: ${msg}${trace}
)。
如果config.warnHandle存在config.warnHandler.call(null, msg, vm, trace)
-
Vue.util.extend
extend (to: Object, _from: ?Object):Object Object類型淺拷貝方法代碼在shared/util.js
-
Vue.util.mergeOptions
合并,vue實例化和實現繼承的核心方法,代碼在shared/options.jsmergeOptions (parent: Object,child: Object,vm?: Component) 先通過normalizeProps、normalizeInject、normalizeDirectives以Object-base標準化,然后依據strats合并策略進行合并。strats是對data、props、watch、methods等實例化參數的合并策略。除此之外還有defaultStrat默認策略。后期暴露的mixin和Vue.extend()就是從這里出來的。[官網解釋][1]
-
Vue.util.defineReactive
大家都知道的數據劫持核心方法,代碼在shared/util.jsdefineReactive (obj: Object,key: string,val: any,customSetter?: ?Function,shallow?: boolean)
4.instance/index.js Vue對象生成文件
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) {// 判斷是否是new調用。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._init(options)內部方法,./init.js
initMixin(Vue)
/*** ./state.js* 添加屬性和方法* Vue.prototype.$data * Vue.prototype.$props* Vue.prototype.$watch* Vue.prototype.$set* Vue.prototype.$delete*/
stateMixin(Vue)
/*** ./event.js* 添加實例事件* Vue.prototype.$on* Vue.prototype.$once* Vue.prototype.$off* Vue.prototype.$emit*/
eventsMixin(Vue)
/*** ./lifecycle.js* 添加實例生命周期方法* Vue.prototype._update* Vue.prototype.$forceUpdate* Vue.prototype.$destroy*/
lifecycleMixin(Vue)
/*** ./render.js* 添加實例渲染方法* 通過執行installRenderHelpers(Vue.prototype);為實例添加很多helper* Vue.prototype.$nextTick* Vue.prototype._render*/
renderMixin(Vue)export default Vue
5.instance/init.js
初始化,完成主組件的所有動作的主線。從這兒出發可以理清observer、watcher、compiler 、render等
import config from '../config'
import { initProxy } from './proxy'
import { initState } from './state'
import { initRender } from './render'
import { initEvents } from './events'
import { mark, measure } from '../util/perf'
import { initLifecycle, callHook } from './lifecycle'
import { initProvide, initInjections } from './inject'
import { extend, mergeOptions, formatComponentName } from '../util/index'let uid = 0export function initMixin (Vue: Class<Component>) {Vue.prototype._init = function (options?: Object) {const vm: Component = this// a uidvm._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 observedvm._isVue = true// merge optionsif (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 selfvm._self = vminitLifecycle(vm)initEvents(vm)/*** 添加vm.$createElement vm.$vnode vm.$slots vm.* 創建vm.$attrs / vm.$listeners 并且轉換為getter和setter* */initRender(vm)callHook(vm, 'beforeCreate')initInjections(vm) // resolve injections before data/props vm.$scopedSlots /*** 1、創建 vm._watchers = [];* 2、執行if (opts.props) { initProps(vm, opts.props); } 驗證props后調用defineReactive轉化,并且代理數據proxy(vm, "_props", key);* 3、執行if (opts.methods) { initMethods(vm, opts.methods); } 然后vm[key] = methods[key] == null ? noop : bind(methods[key], vm);* 4、處理data,* if (opts.data) {* initData(vm);* } else {* observe(vm._data = {}, true /* asRootData */);* }* 5、執行initData:* (1)先判斷data的屬性是否有與methods和props值同名* (2)獲取vm.data(如果為function,執行getData(data, vm)),代理proxy(vm, "_data", key);* (3)執行 observe(data, true /* asRootData */);遞歸觀察* 6、完成observe,具體看解釋*/initState(vm)initProvide(vm) // resolve provide after data/propscallHook(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)}}
}
二、observe 響應式數據轉換
1.前置方法 observe(value, asRootData)
function observe (value, asRootData) {// 如果value不是是Object 或者是VNode這不用轉換if (!isObject(value) || value instanceof VNode) {return}var ob;// 如果已經轉換就復用if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {ob = value.__ob__;} else if (//一堆必要的條件判斷observerState.shouldConvert &&!isServerRendering() &&(Array.isArray(value) || isPlainObject(value)) &&Object.isExtensible(value) &&!value._isVue) {//這才是observe主體ob = new Observer(value);}if (asRootData && ob) {ob.vmCount++;}return ob
}
2.Observer 類
var Observer = function Observer (value) {// 當asRootData = true時,其實可以將value當做vm.$options.data,后面都這樣方便理解this.value = value;/*** 為vm.data創建一個dep實例,可以理解為一個專屬事件列表維護對象* 例如: this.dep = { id : 156, subs : [] }* 實例方法: this.dep.__proto__ = { addSub, removeSub, depend, notify, constructor }*/this.dep = new Dep();//記錄關聯的vm實例的數量this.vmCount = 0;//為vm.data 添加__ob__屬性,值為當前observe實例,并且轉化為響應式數據。所以看一個value是否為響應式就可以看他有沒有__ob__屬性def(value, '__ob__', this);//響應式數據轉換分為數組、對象兩種。if (Array.isArray(value)) {var augment = hasProto? protoAugment: copyAugment;augment(value, arrayMethods, arrayKeys);this.observeArray(value);} else {//對象的轉換,而且walk是Observer的實例方法,請記住this.walk(value);}
};
3.walk
該方法要將vm.data的所有屬性都轉化為getter/setter模式,所以vm.data只能是Object。數組的轉換不一樣,這里暫不做講解。
Observer.prototype.walk = function walk (obj) {// 得到key的列表var keys = Object.keys(obj);for (var i = 0; i < keys.length; i++) {//核心方法:定義響應式數據的方法 defineReactive(對象, 屬性, 值);這樣看是不是就很爽了defineReactive(obj, keys[i], obj[keys[i]]);}
};
4.defineReactive(obj, key, value)
function defineReactive (obj,key,val,customSetter, //自定義setter,為了測試shallow //是否只轉換這一個屬性后代不管控制參數,false :是,true : 否
) {/*** 又是一個dep實例,其實作用與observe中的dep功能一樣,不同點:* 1.observe實例的dep對象是父級vm.data的訂閱者維護對象* 2.這個dep是vm.data的屬性key的訂閱者維護對象,因為val有可能也是對象* 3.這里的dep沒有寫this.dep是因為defineReactive是一個方法,不是構造函數,所以使用閉包鎖在內存中*/var dep = new Dep();// 獲取key的屬性描述符var property = Object.getOwnPropertyDescriptor(obj, key);// 如果key屬性不可設置,則退出該函數if (property && property.configurable === false) {return}// 為了配合那些已經的定義了getter/setter的情況var getter = property && property.get;var setter = property && property.set;//遞歸,因為沒有傳asRootData為true,所以vm.data的vmCount是部分計數的。因為它還是屬于vm的數據var childOb = !shallow && observe(val);/*** 全部完成后observe也就完成了。但是,每個屬性的dep都沒啟作用。* 這就是所謂的依賴收集了,后面繼續。*/Object.defineProperty(obj, key, {enumerable: true,configurable: true,get: function reactiveGetter () {var value = getter ? getter.call(obj) : val;if (Dep.target) {dep.depend();if (childOb) {childOb.dep.depend();if (Array.isArray(value)) {dependArray(value);}}}return value},set: function reactiveSetter (newVal) {var value = getter ? getter.call(obj) : val;/* eslint-disable no-self-compare */if (newVal === value || (newVal !== newVal && value !== value)) {return}/* eslint-enable no-self-compare */if (process.env.NODE_ENV !== 'production' && customSetter) {customSetter();}if (setter) {setter.call(obj, newVal);} else {val = newVal;}childOb = !shallow && observe(newVal);dep.notify();}});
}
三、依賴收集
一些個人理解:1、Watcher 訂閱者可以將它理解為,要做什么。具體的體現就是Watcher的第二個參數expOrFn。2、Observer 觀察者其實觀察的體現就是getter/setter能夠觀察數據的變化(數組的實現不同)。3、dependency collection 依賴收集訂閱者(Watcher)是干事情的,是一些指令、方法、表達式的執行形式。它運行的過程中肯定離不開數據,所以就成了這些數據的依賴項目。因為離不開^_^數據。數據是肯定會變的,那么數據變了就得通知數據的依賴項目(Watcher)讓他們再執行一下。依賴同一個數據的依賴項目(Watcher)可能會很多,為了保證能夠都通知到,所以需要收集一下。4、Dep 依賴收集器構造函數因為數據是由深度的,在不同的深度有不同的依賴,所以我們需要一個容器來裝起來。Dep.target的作用是保證數據在收集依賴項(Watcher)時,watcher是對這個數據依賴的,然后一個個去收集的。
1、Watcher
Watcher (vm, expOrFn, cb, options)
參數:
{string | Function} expOrFn
{Function | Object} callback
{Object} [options]{boolean} deep{boolean} user{boolean} lazy{boolean} sync
在Vue的整個生命周期當中,會有4類地方會實例化Watcher:Vue實例化的過程中有watch選項Vue實例化的過程中有computed計算屬性選項Vue原型上有掛載$watch方法: Vue.prototype.$watch,可以直接通過實例調用this.$watch方法Vue生成了render函數,更新視圖時Watcher接收的參數當中expOrFn定義了用以獲取watcher的getter函數。expOrFn可以有2種類型:string或function.若為string類型,
首先會通過parsePath方法去對string進行分割(僅支持.號形式的對象訪問)。在除了computed選項外,其他幾種實例化watcher的方式都
是在實例化過程中完成求值及依賴的收集工作:this.value = this.lazy ? undefined : this.get().在Watcher的get方法中:
var Watcher = function Watcher (vm,expOrFn,cb,options
) {this.vm = vm;vm._watchers.push(this);// optionsif (options) {this.deep = !!options.deep;this.user = !!options.user;this.lazy = !!options.lazy;this.sync = !!options.sync;} else {this.deep = this.user = this.lazy = this.sync = false;}//相關屬性this.cb = cb;this.id = ++uid$2; // uid for batchingthis.active = true;this.dirty = this.lazy; // for lazy watchers//this.deps = [];this.newDeps = [];//set類型的idsthis.depIds = new _Set();this.newDepIds = new _Set();// 表達式this.expression = process.env.NODE_ENV !== 'production'? expOrFn.toString(): '';// 創建一個getterif (typeof expOrFn === 'function') {this.getter = expOrFn;} else {this.getter = parsePath(expOrFn);if (!this.getter) {this.getter = function () {};process.env.NODE_ENV !== 'production' && warn("Failed watching path: \"" + expOrFn + "\" " +'Watcher only accepts simple dot-delimited paths. ' +'For full control, use a function instead.',vm);}}this.value = this.lazy? undefined: this.get();//執行get收集依賴項
};
2、Watcher.prototype.get
通過設置觀察值(this.value)調用this.get方法,執行this.getter.call(vm, vm),這個過程中只要獲取了某個響應式數據。那么肯定會觸發該數據的getter方法。因為當前的Dep.target = watcher。所以就將該watcher作為了這個響應數據的依賴項。因為watcher在執行過程中的確需要、使用了它、所以依賴它。
Watcher.prototype.get = function get () {//將這個watcher觀察者實例添加到Dep.target,表明當前為this.expressoin的依賴收集時間pushTarget(this);var value;var vm = this.vm;try {/*** 執行this.getter.call(vm, vm):* 1、如果是function則相當于vm.expOrFn(vm),只要在這個方法執行的過程中有從vm上獲取屬性值的都會觸發該屬性值的get方法從而完成依賴收集。因為現在Dep.target=this. * 2、如果是字符串(如a.b),那么this.getter.call(vm, vm)就相當于vm.a.b*/ value = this.getter.call(vm, vm);} catch (e) {if (this.user) {handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));} else {throw e}} finally {// "touch" every property so they are all tracked as// dependencies for deep watchingif (this.deep) {traverse(value);}popTarget();this.cleanupDeps();}return value
};
3、getter/setter
Object.defineProperty(obj, key, {enumerable: true,configurable: true,get: function reactiveGetter () {var value = getter ? getter.call(obj) : val;if (Dep.target) {//依賴收集,這里又饒了一圈,看后面的解釋dep.depend();if (childOb) {childOb.dep.depend();if (Array.isArray(value)) {dependArray(value);}}}return value},set: function reactiveSetter (newVal) {var value = getter ? getter.call(obj) : val;/* eslint-disable no-self-compare */if (newVal === value || (newVal !== newVal && value !== value)) {return}/* eslint-enable no-self-compare */if (process.env.NODE_ENV !== 'production' && customSetter) {customSetter();}if (setter) {setter.call(obj, newVal);} else {val = newVal;}childOb = !shallow && observe(newVal);//數據變動出發所有依賴項dep.notify();}});
- 依賴收集具體動作:
//調用的自己dep的實例方法
Dep.prototype.depend = function depend () {if (Dep.target) {//調用的是當前Watcher實例的addDe方法,并且把dep對象傳過去了Dep.target.addDep(this);}
};Watcher.prototype.addDep = function addDep (dep) {var id = dep.id;if (!this.newDepIds.has(id)) {//為這個watcher統計內部依賴了多少個數據,以及其他公用該數據的watcherthis.newDepIds.add(id);this.newDeps.push(dep);if (!this.depIds.has(id)) {//繼續為數據收集依賴項目的步驟dep.addSub(this);}}
};
Dep.prototype.addSub = function addSub (sub) {this.subs.push(sub);
};
- 數據變動出發依賴動作:
Dep.prototype.notify = function notify () {// stabilize the subscriber list firstvar subs = this.subs.slice();for (var i = 0, l = subs.length; i < l; i++) {subs[i].update();}
};
//對當前watcher的處理
Watcher.prototype.update = function update () {/* istanbul ignore else */if (this.lazy) {this.dirty = true;} else if (this.sync) {this.run();} else {queueWatcher(this);}
};
//把一個觀察者推入觀察者隊列。
//具有重復id的作業將被跳過,除非它是
//當隊列被刷新時被推。
export function queueWatcher (watcher: Watcher) {const id = watcher.idif (has[id] == null) {has[id] = trueif (!flushing) {queue.push(watcher)} else {// if already flushing, splice the watcher based on its id// if already past its id, it will be run next immediately.let i = queue.length - 1while (i > index && queue[i].id > watcher.id) {i--}queue.splice(i + 1, 0, watcher)}// queue the flushif (!waiting) {waiting = truenextTick(flushSchedulerQueue)}}
}