Vue框架中的基本原理可能你們都基本瞭解了,可是尚未漫遊一下源碼。
因此,以爲仍是有必要跑一下。
因爲是代碼漫遊,因此大部分爲關鍵性代碼,以主線路和主要分支的代碼爲主,大部分理解都寫在代碼註釋中。複製代碼
文件結構1-->4,代碼執行順序4-->1html
web不一樣平臺入口;vue
/* @flow */
import Vue from './runtime/index'
export default Vue複製代碼
爲Vue配置一些屬性方法node
/* @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) : undefined
return 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複製代碼
/* @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 = () => 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.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.js
Vue.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 / filter initAssetRegisters(Vue) }複製代碼
Vue.util對象的部分解釋:react
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)複製代碼
extend (to: Object, _from: ?Object):Object Object類型淺拷貝方法代碼在shared/util.js複製代碼
mergeOptions (
parent: Object,
child: Object,
vm?: Component複製代碼
)defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean複製代碼
) 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複製代碼
初始化,完成主組件的全部動做的主線。從這兒出發能夠理清observer、watcher、compiler 、render等ios
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 = 0
export function initMixin (Vue: Class<Component>) {
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// a uid
vm._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 observed
vm._isVue = true
// merge options
if (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 self
vm._self = vm
initLifecycle(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
/**
* 一、建立 vm._watchers = [];
* 二、執行if (opts.props) { initProps(vm, opts.props); } 驗證props後調用defineReactive轉化,而且代理數據proxy(vm, "_props", key);
* 三、執行if (opts.methods) { initMethods(vm, opts.methods); } 而後vm[key] = methods[key] == null ? noop : bind(methods[key], vm);
* 四、處理data,
* if (opts.data) {
* initData(vm);
* } else {
* observe(vm._data = {}, true /* asRootData */);
* }
* 五、執行initData:
* (1)先判斷data的屬性是否有與methods和props值同名
* (2)獲取vm.data(若是爲function,執行getData(data, vm)),代理proxy(vm, "_data", key);
* (3)執行 observe(data, true /* asRootData */);遞歸觀察
* 六、完成observe,具體看解釋
*/
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(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)
}
}
}複製代碼
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
}複製代碼
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);
}
};複製代碼
該方法要將vm.data的全部屬性都轉化爲getter/setter模式,因此vm.data只能是Object。數組的轉換不同,這裏暫不作講解。git
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]]);
}
};複製代碼
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();
}
});
}複製代碼
一些我的理解:
一、Watcher 訂閱者
能夠將它理解爲,要作什麼。具體的體現就是Watcher的第二個參數expOrFn。
二、Observer 觀察者
其實觀察的體現就是getter/setter可以觀察數據的變化(數組的實現不一樣)。
三、dependency collection 依賴收集
訂閱者(Watcher)是幹事情的,是一些指令、方法、表達式的執行形式。它運行的過程當中確定離不開數據,因此就成了這些數據的依賴項目。由於離不開^_^數據。
數據是確定會變的,那麼數據變了就得通知數據的依賴項目(Watcher)讓他們再執行一下。
依賴同一個數據的依賴項目(Watcher)可能會不少,爲了保證可以都通知到,因此須要收集一下。
四、Dep 依賴收集器構造函數
由於數據是由深度的,在不一樣的深度有不一樣的依賴,因此咱們須要一個容器來裝起來。
Dep.target的做用是保證數據在收集依賴項(Watcher)時,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);
// options
if (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 batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
//
this.deps = [];
this.newDeps = [];
//set類型的ids
this.depIds = new _Set();
this.newDepIds = new _Set();
// 表達式
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: '';
// 建立一個getter
if (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收集依賴項
};複製代碼
經過設置觀察值(this.value)調用this.get方法,執行this.getter.call(vm, vm),這個過程當中只要獲取了某個響應式數據。那麼確定會觸發該數據的getter方法。由於當前的Dep.target = watcher。因此就將該watcher做爲了這個響應數據的依賴項。由於watcher在執行過程當中的確須要、使用了它、因此依賴它。github
Watcher.prototype.get = function get () {
//將這個watcher觀察者實例添加到Dep.target,代表當前爲this.expressoin的依賴收集時間
pushTarget(this);
var value;
var vm = this.vm;
try {
/**
* 執行this.getter.call(vm, vm):
* 一、若是是function則至關於vm.expOrFn(vm),只要在這個方法執行的過程當中有從vm上獲取屬性值的都會觸發該屬性值的get方法從而完成依賴收集。由於如今Dep.target=this.
* 二、若是是字符串(如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 watching
if (this.deep) {
traverse(value);
}
popTarget();
this.cleanupDeps();
}
return value
};複製代碼
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();
}
});複製代碼
- 依賴收集具體動做:web
//調用的本身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統計內部依賴了多少個數據,以及其餘公用該數據的watcher
this.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);
};複製代碼
- 數據變更出發依賴動做:express
Dep.prototype.notify = function notify () {
// stabilize the subscriber list first
var 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.id
if (has[id] == null) {
has[id] = true
if (!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 - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// queue the flush
if (!waiting) {
waiting = true
nextTick(flushSchedulerQueue)
}
}
}複製代碼