雖然vue3已經出來很久了,但我覺得vue.js的源碼還是非常值得去學習一下。vue.js里面封裝的很多工具類在我們平時工作項目中也會經常用到。所以我近期會對vue.js的源碼進行解讀,分享值得去學習的代碼片段,這篇文章將會持續(xù)更新。
一、2400~4000代碼有哪些內容?:
1.children 的規(guī)范化:normalizeArrayChildren
2.組件實例化:initInjections
3.slot插槽函數:resolveSlots,normalizeScopedSlots,normalizeScopedSlot,proxyNormalSlot,renderSlot
4.Vue 的各類渲染方法--輔助函數:
markOnce;// 標記v-once
toNumber;// 轉換成Number類型
toString;//轉換成字符串
renderList;//生成列表VNode
renderSlot;//生成解析slot節(jié)點
looseEqual;
looseIndexOf;
renderStatic;//生成靜態(tài)元素
resolveFilter;// 獲取過濾器
checkKeyCodes;//檢查鍵盤事件keycode
bindObjectProps;//綁定對象屬性
createTextVNode;//創(chuàng)建文本VNod
createEmptyVNode;//創(chuàng)建空節(jié)點VNode
resolveScopedSlots;//獲取作用域插槽
bindObjectListeners;//處理v-on=’{}'到vnode data上
bindDynamicKeys;//處理動態(tài)屬性名
prependModifier;//處理修飾符
二.2400~4000行代碼的重點:
1.vue的事件機制
①.監(jiān)聽事件:$on
②.監(jiān)聽事件,只監(jiān)聽1次:$once
③.移除自定義事件監(jiān)聽器:$off
④.觸發(fā)事件: $emit
2.函數式組件的實現
createFunctionalComponent
3.組件的渲染和更新過程
componentVNodeHooks
在組件初始化的時候實現init、prepatch、insert、destroy鉤子函數
三、2400~4000行的代碼解讀:
//children 的規(guī)范化,simpleNormalizeChildren和normalizeChildren都是用來把children由樹狀結構變成一維數組
// 模板編譯器試圖通過在編譯時靜態(tài)分析模板來最小化規(guī)范化的需要
// 對于純HTML標記,可以完全跳過規(guī)范化,因為生成的呈現函數保證返回Array<VNode>。有兩種情況需要額外的規(guī)范化:
// 當子級包含組件時-因為功能組件可能返回數組而不是單個根。在這種情況下,只需要一個簡單的規(guī)范化—如果任何子對象是數組,
// 我們就用Array.prototype.concat將整個對象展平。它保證只有1級深度,因為功能組件已經規(guī)范化了它們自己的子級
function simpleNormalizeChildren (children) {
for (var i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
// 2.當子級包含總是生成嵌套數組的構造時,例如<template>、<slot>、v-for,或者當子級由用戶提供手寫的呈現函數/JSX時。
// 在這種情況下,需要完全正?;?,以滿足所有可能類型的兒童價值觀。
function normalizeChildren (children) {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
// node節(jié)點的判斷條件
function isTextNode (node) {
return isDef(node) && isDef(node.text) && isFalse(node.isComment)
}
//children 的規(guī)范化,normalizeArrayChildren接收 2 個參數,children 表示要規(guī)范的子節(jié)點,nestedIndex 表示嵌套的索引
function normalizeArrayChildren (children, nestedIndex) {
var res = [];
var i, c, lastIndex, last;
//遍歷children,
for (i = 0; i < children.length; i++) {
//將單個節(jié)點賦值給c
c = children[i];
//判斷c的類型,如果是一個數組類型,則遞歸調用 normalizeArrayChildren;
//否則通過 createTextVNode 方法轉換成 VNode 類型;
if (isUndef(c) || typeof c === 'boolean') { continue }
lastIndex = res.length - 1;
last = res[lastIndex];
//如果是一個數組類型,則遞歸調用 normalizeArrayChildren
if (Array.isArray(c)) {
if (c.length > 0) {
// 如果 children 是一個列表并且列表還存在嵌套的情況,則根據 nestedIndex 去更新它的 key
c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i));
if (isTextNode(c[0]) && isTextNode(last)) {
res[lastIndex] = createTextVNode(last.text + (c[0]).text);
c.shift();
}
res.push.apply(res, c);
}
} else if (isPrimitive(c)) {
if (isTextNode(last)) {
//通過 createTextVNode 方法轉換成 VNode 類型
res[lastIndex] = createTextVNode(last.text + c);
} else if (c !== '') {
res.push(createTextVNode(c));
}
} else {
if (isTextNode(c) && isTextNode(last)) {
res[lastIndex] = createTextVNode(last.text + c.text);
} else {
if (isTrue(children._isVList) &&
isDef(c.tag) &&
isUndef(c.key) &&
isDef(nestedIndex)) {
c.key = "__vlist" + nestedIndex + "_" + i + "__";
}
res.push(c);
}
}
}
return res
}
/* initProvide的作用就是將$options里的provide賦值到當前實例上 */
function initProvide (vm) {
//如果provide存在,當它是函數時執(zhí)行該返回,否則直接將provide保存到Vue實例的_provided屬性上
var provide = vm.$options.provide;
if (provide) {
vm._provided = typeof provide === 'function'
? provide.call(vm)
: provide;
}
}
//組件實例化,初始化Inject參數, initInjections在初始化data/props之前被調用,主要作用是初始化vue實例的inject
function initInjections (vm) {
//遍歷祖先節(jié)點,獲取對應的inject
var result = resolveInject(vm.$options.inject, vm);
if (result) {
// toggleObserving是vue內部對邏輯的一個優(yōu)化,就是禁止掉根組件 props的依賴收集
toggleObserving(false);
Object.keys(result).forEach(function (key) {
//將key編程響應式,這樣就可以訪問該元素
{
defineReactive$$1(vm, key, result[key], function () {
warn(
"Avoid mutating an injected value directly since the changes will be " +
"overwritten whenever the provided component re-renders. " +
"injection being mutated: \"" + key + "\"",
vm
);
});
}
});
toggleObserving(true);
}
}
// 確定Inject,vm指當前組件的實例
function resolveInject (inject, vm) {
if (inject) {
// inject is :any because flow is not smart enough to figure out cached
var result = Object.create(null);
//如果有符號類型,調用Reflect.ownKeys()返回所有的key,再調用filter
var keys = hasSymbol
? Reflect.ownKeys(inject)
: Object.keys(inject);
//獲取所有的key,此時keys就是個字符串數組
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
// #6574 in case the inject object is observed...
if (key === '__ob__') { continue }
var provideKey = inject[key].from;
var source = vm;
while (source) {
//如果source存在_provided 且 含有provideKey這個屬性,則將值保存到result[key]中
if (source._provided && hasOwn(source._provided, provideKey)) {
result[key] = source._provided[provideKey];
break
}
// 否則將source賦值給父Vue實例,直到找到對應的providekey為止
source = source.$parent;
}
// 如果最后source不存在,即沒有從當前實例或祖先實例的_provide找到privideKey這個key
if (!source) {
// 如果有定義defult,則使用默認值
if ('default' in inject[key]) {
var provideDefault = inject[key].default;
result[key] = typeof provideDefault === 'function'
? provideDefault.call(vm)
: provideDefault;
} else {
warn(("Injection \"" + key + "\" not found"), vm);
}
}
}
return result
}
}
/* */
/**
* 主要作用是將children VNodes轉化成一個slots對象,處理組件slot,返回slot插槽對象
* children指占位符Vnode里的內容
* context指占位符Vnode所在的vue實例
*/
function resolveSlots (
children,
context
) {
// 判斷是否有children,即是否有插槽VNode
if (!children || !children.length) {
return {}
}
var slots = {};
// 遍歷每一個子節(jié)點
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
// data為VNodeData,保存父組件傳遞到子組件的props以及attrs等
var data = child.data;
//移出slot,刪除該節(jié)點attrs的slot
if (data && data.attrs && data.attrs.slot) {
delete data.attrs.slot;
}
// 判斷是否為具名插槽,如果為具名插槽,還需要 子組件 / 函數子組件 渲染上下文一致
// 當需要向子組件的子組件傳遞具名插槽時,不會保持插槽的名字
if ((child.context === context || child.fnContext === context) &&
data && data.slot != null
) {
var name = data.slot;
var slot = (slots[name] || (slots[name] = []));
//處理父組件采用template形式的插槽
if (child.tag === 'template') {
slot.push.apply(slot, child.children || []);
} else {
slot.push(child);
}
} else {
//返回匿名default插槽VNode數組
(slots.default || (slots.default = [])).push(child);
}
}
// 忽略僅僅包含whitespace的插槽
for (var name$1 in slots) {
if (slots[name$1].every(isWhitespace)) {
delete slots[name$1];
}
}
return slots
}
// 方法用于判斷指定字符是否為空白字符,空白符包含:空格、tab鍵、換行符
function isWhitespace (node) {
return (node.isComment && !node.asyncFactory) || node.text === ' '
}
/* 是否為異步占位 */
function isAsyncPlaceholder (node) {
return node.isComment && node.asyncFactory
}
/*normalizeScopedSlots函數的核心就是返回res對象,其key為slotTarget,value為fn */
//slots: 某節(jié)點 data 屬性上 scopedSlots
//normalSlots: 當前節(jié)點下的普通插槽
//prevSlots 當前節(jié)點下的特殊插槽
function normalizeScopedSlots (
slots,
normalSlots,
prevSlots
) {
var res;
//判斷是否擁有普通插槽
var hasNormalSlots = Object.keys(normalSlots).length > 0;
var isStable = slots ? !!slots.$stable : !hasNormalSlots;
var key = slots && slots.$key;
if (!slots) {
res = {};
} else if (slots._normalized) {
return slots._normalized
} else if (
isStable &&
prevSlots &&
prevSlots !== emptyObject &&
// slots $key 值與 prevSlots $key 相等
key === prevSlots.$key &&
//slots中沒有普通插槽
!hasNormalSlots &&
//prevSlots中沒有普通插槽
!prevSlots.$hasNormal
) {
return prevSlots
} else {
res = {};
//遍歷作用域插槽
for (var key$1 in slots) {
if (slots[key$1] && key$1[0] !== '$') {
res[key$1] = normalizeScopedSlot(normalSlots, key$1, slots[key$1]);
}
}
}
// 對普通插槽進行遍歷,將slot代理到scopeSlots上
for (var key$2 in normalSlots) {
if (!(key$2 in res)) {
res[key$2] = proxyNormalSlot(normalSlots, key$2);
}
}
// avoriaz seems to mock a non-extensible $scopedSlots object
// and when that is passed down this would cause an error
if (slots && Object.isExtensible(slots)) {
(slots)._normalized = res;
}
// $key , $hasNormal , $stable 是直接使用 vue 內部對 Object.defineProperty 封裝好的 def() 方法進行賦值的
def(res, '$stable', isStable);
def(res, '$key', key);
def(res, '$hasNormal', hasNormalSlots);
return res
}
//將scopeSlots對應屬性和方法掛載到scopeSlots,生成閉包,返回一個名為normalized的函數,$scopedSlots對象中的值就是此函數
function normalizeScopedSlot(normalSlots, key, fn) {
var normalized = function () {
var res = arguments.length ? fn.apply(null, arguments) : fn({});
res = res && typeof res === 'object' && !Array.isArray(res)
? [res] // single vnode
: normalizeChildren(res);
var vnode = res && res[0];
return res && (
!vnode ||
(res.length === 1 && vnode.isComment && !isAsyncPlaceholder(vnode)) // #9658, #10391
) ? undefined
: res
};
// this is a slot using the new v-slot syntax without scope. although it is
// compiled as a scoped slot, render fn users would expect it to be present
// on this.$slots because the usage is semantically a normal slot.
if (fn.proxy) {
Object.defineProperty(normalSlots, key, {
get: normalized,
enumerable: true,
configurable: true
});
}
return normalized
}
// 將slot代理到scopeSlots上
function proxyNormalSlot(slots, key) {
return function () { return slots[key]; }
}
/* */
/**
* 用于呈現v-for列表的運行時幫助程序
*/
function renderList (
val,
render
) {
var ret, i, l, keys, key;
//如果val為數組,則遍歷val
if (Array.isArray(val) || typeof val === 'string') {
ret = new Array(val.length);
// 調用傳入的函數,把值傳入,數組保存結果
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
//如果val為數字類型
} else if (typeof val === 'number') {
ret = new Array(val);
// 調用傳入的函數,把值傳入,數組保存結果
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
//如果val為object類型,則遍歷對象
} else if (isObject(val)) {
if (hasSymbol && val[Symbol.iterator]) {
ret = [];
var iterator = val[Symbol.iterator]();
var result = iterator.next();
// 調用傳入的函數,把值傳入,數組保存結果
while (!result.done) {
ret.push(render(result.value, ret.length));
result = iterator.next();
}
} else {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
}
if (!isDef(ret)) {
ret = [];
}
(ret)._isVList = true;
return ret
}
/* */
// 調用renderSlot用函數的返回值進行渲染
// renderSlot函數會根據插槽名字找到對應的作用域Slot包裝成的函數,
// 然后執(zhí)行它,把子組件內的數據{ child:child }傳進去
function renderSlot (
name,//插槽名
fallbackRender,//插槽默認內容生成的 vnode 數組
props,// props 對象
bindObject //v-bind 綁定對象
) {
var scopedSlotFn = this.$scopedSlots[name];
var nodes;
if (scopedSlotFn) {
props = props || {};
if (bindObject) {
if (!isObject(bindObject)) {
warn('slot v-bind without argument expects an Object', this);
}
props = extend(extend({}, bindObject), props);
}
nodes =
scopedSlotFn(props) ||
(typeof fallbackRender === 'function' ? fallbackRender() : fallbackRender);
} else {
nodes =
this.$slots[name] ||
(typeof fallbackRender === 'function' ? fallbackRender() : fallbackRender);
}
var target = props && props.slot;
if (target) {
return this.$createElement('template', { slot: target }, nodes)
} else {
return nodes
}
}
/* */
/**
*找到我們寫的過濾器,并將參數傳入進去
*/
function resolveFilter (id) {
// resolveAsset用于獲取資源,也就是獲取組件的構造函數
return resolveAsset(this.$options, 'filters', id, true) || identity
}
/* 檢查按下的鍵,是否和配置的鍵值對匹配 */
function isKeyNotMatch (expect, actual) {
if (Array.isArray(expect)) {
return expect.indexOf(actual) === -1
} else {
return expect !== actual
}
}
/**
* 用于檢查config.prototype中的鍵代碼的運行時幫助程序,以Vue.prototype的形式公開
*/
function checkKeyCodes (
eventKeyCode,
key,
builtInKeyCode,
eventKeyName,
builtInKeyName
) {
// 比如 key 傳入的是自定義名字 aaaa
// keyCode 從Vue 定義的 keyNames 獲取 aaaa 的實際數字
// keyName 從 Vue 定義的 keyCode 獲取 aaaa 的別名
// 并且以用戶定義的為準,可以覆蓋Vue 內部定義的
var mappedKeyCode = config.keyCodes[key] || builtInKeyCode;
// 該鍵只在 Vue 內部定義的 keyCode 中
if (builtInKeyName && eventKeyName && !config.keyCodes[key]) {
return isKeyNotMatch(builtInKeyName, eventKeyName)
// 該鍵只在 用戶自定義配置的 keyCode 中
} else if (mappedKeyCode) {
return isKeyNotMatch(mappedKeyCode, eventKeyCode)
//原始鍵名
} else if (eventKeyName) {
return hyphenate(eventKeyName) !== key
}
return eventKeyCode === undefined
}
/**
* 用于將v-bind=“object”合并到VNode數據中的運行時幫助程序
*/
function bindObjectProps (
data,
tag,
value,
asProp,
isSync
) {
if (value) {
if (!isObject(value)) {
warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
var hash;
var loop = function ( key ) {
if (
key === 'class' ||
key === 'style' ||
isReservedAttribute(key)
) {
hash = data;
} else {
var type = data.attrs && data.attrs.type;
hash = asProp || config.mustUseProp(tag, type, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {});
}
var camelizedKey = camelize(key);
var hyphenatedKey = hyphenate(key);
if (!(camelizedKey in hash) && !(hyphenatedKey in hash)) {
hash[key] = value[key];
if (isSync) {
var on = data.on || (data.on = {});
on[("update:" + key)] = function ($event) {
value[key] = $event;
};
}
}
};
for (var key in value) loop( key );
}
}
return data
}
/* */
/**
* 生成靜態(tài)元素
*/
function renderStatic (
index,
isInFor
) {
var cached = this._staticTrees || (this._staticTrees = []);
var tree = cached[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree.
if (tree && !isInFor) {
return tree
}
// otherwise, render a fresh tree.
tree = cached[index] = this.$options.staticRenderFns[index].call(
this._renderProxy,
null,
this // for render fns generated for functional component templates
);
markStatic(tree, ("__static__" + index), false);
return tree
}
/**
* 標記v-once
*/
function markOnce (
tree,
index,
key
) {
markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true);
return tree
}
// 標記靜態(tài)元素
function markStatic (
tree,
key,
isOnce
) {
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
if (tree[i] && typeof tree[i] !== 'string') {
markStaticNode(tree[i], (key + "_" + i), isOnce);
}
}
} else {
markStaticNode(tree, key, isOnce);
}
}
//標記靜態(tài)節(jié)點
function markStaticNode (node, key, isOnce) {
node.isStatic = true;
node.key = key;
node.isOnce = isOnce;
}
/* //處理v-on=’{}'到vnode data上 */
function bindObjectListeners (data, value) {
if (value) {
if (!isPlainObject(value)) {
warn(
'v-on without argument expects an Object value',
this
);
} else {
var on = data.on = data.on ? extend({}, data.on) : {};
for (var key in value) {
var existing = on[key];
var ours = value[key];
on[key] = existing ? [].concat(existing, ours) : ours;
}
}
}
return data
}
/* 獲取作用域插槽 */
function resolveScopedSlots (
fns, // see flow/vnode
res,
// the following are added in 2.6
hasDynamicKeys,
contentHashKey
) {
res = res || { $stable: !hasDynamicKeys };
for (var i = 0; i < fns.length; i++) {
var slot = fns[i];
if (Array.isArray(slot)) {
resolveScopedSlots(slot, res, hasDynamicKeys);
} else if (slot) {
// marker for reverse proxying v-slot without scope on this.$slots
if (slot.proxy) {
slot.fn.proxy = true;
}
res[slot.key] = slot.fn;
}
}
if (contentHashKey) {
(res).$key = contentHashKey;
}
return res
}
/*//處理動態(tài)屬性名 */
function bindDynamicKeys (baseObj, values) {
for (var i = 0; i < values.length; i += 2) {
var key = values[i];
if (typeof key === 'string' && key) {
baseObj[values[i]] = values[i + 1];
} else if (key !== '' && key !== null) {
// null is a special value for explicitly removing a binding
warn(
("Invalid value for dynamic directive argument (expected string or null): " + key),
this
);
}
}
return baseObj
}
//處理修飾符
// 幫助程序將修改器運行時標記動態(tài)追加到事件名稱。
// 請確保僅在值已為字符串時追加,否則將轉換為字符串并導致類型檢查丟失。
function prependModifier (value, symbol) {
return typeof value === 'string' ? symbol + value : value
}
/* 安裝渲染工具函數,大多數服務于編譯器編譯出來的代碼 */
function installRenderHelpers (target) {
target._o = markOnce;// 標記v-once
target._n = toNumber;// 轉換成Number類型
target._s = toString;//轉換成字符串
target._l = renderList;//生成列表VNode
target._t = renderSlot;//生成解析slot節(jié)點
target._q = looseEqual;
target._i = looseIndexOf;
target._m = renderStatic;//生成靜態(tài)元素
target._f = resolveFilter;// 獲取過濾器
target._k = checkKeyCodes;//檢查鍵盤事件keycode
target._b = bindObjectProps;//綁定對象屬性
target._v = createTextVNode;//創(chuàng)建文本VNod
target._e = createEmptyVNode;//創(chuàng)建空節(jié)點VNode
target._u = resolveScopedSlots;//獲取作用域插槽
target._g = bindObjectListeners;//處理v-on=’{}'到vnode data上
target._d = bindDynamicKeys;//處理動態(tài)屬性名
target._p = prependModifier;//處理修飾符
}
/* */
//創(chuàng)建一個包含渲染要素的函數
function FunctionalRenderContext (
data,//組件的數據
props,//父組件傳遞過來的數據
children,//引用該組件時定義的子節(jié)點
parent,
Ctor//組件的構造對象(Vue.extend()里的那個Sub函數)
) {
var this$1 = this;
var options = Ctor.options;
// 確保functional components中的createElement函數獲得唯一的上下文
var contextVm;
if (hasOwn(parent, '_uid')) {
contextVm = Object.create(parent);
contextVm._original = parent;
} else {
//確保能夠獲得對真實上下文實例的保留
contextVm = parent;
parent = parent._original;
}
var isCompiled = isTrue(options._compiled);
var 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 = function () {
if (!this$1.$slots) {
normalizeScopedSlots(
data.scopedSlots,
this$1.$slots = resolveSlots(children, parent)
);
}
return this$1.$slots
};
Object.defineProperty(this, 'scopedSlots', ({
enumerable: true,
get: function get () {
return normalizeScopedSlots(data.scopedSlots, this.slots())
}
}));
// 對已編譯函數模板的支持
if (isCompiled) {
// 公開renderStatic()的$options
this.$options = options;
// 預解析renderSlot()的插槽
this.$slots = this.slots();
this.$scopedSlots = normalizeScopedSlots(data.scopedSlots, this.$slots);
}
if (options._scopeId) {
this._c = function (a, b, c, d) {
var 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 = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); };
}
}
//渲染輔助函數
installRenderHelpers(FunctionalRenderContext.prototype);
//函數式組件的實現
function createFunctionalComponent (
Ctor,//Ctro:組件的構造對象(Vue.extend()里的那個Sub函數)
propsData, //propsData:父組件傳遞過來的數據(還未驗證)
data,//data:組件的數據
contextVm, //contextVm:Vue實例
children //children:引用該組件時定義的子節(jié)點
) {
var options = Ctor.options;
var props = {};
var propOptions = options.props;
//如果propOptions非空(父組件向當前組件傳入了信息),則遍歷propOptions
if (isDef(propOptions)) {
for (var key in propOptions) {
// 調用validateProp()依次進行檢驗
props[key] = validateProp(key, propOptions, propsData || emptyObject);
}
} else {
if (isDef(data.attrs)) { mergeProps(props, data.attrs); }
if (isDef(data.props)) { mergeProps(props, data.props); }
}
//創(chuàng)建一個函數的上下文
var renderContext = new FunctionalRenderContext(
data,
props,
children,
contextVm,
Ctor
);
//執(zhí)行render函數,參數1為createElement,參數2為renderContext,也就是我們在組件內定義的render函數
var vnode = options.render.call(null, renderContext._c, renderContext);
if (vnode instanceof VNode) {
// 為了避免復用節(jié)點,fnContext 導致命名槽點不匹配的情況,
// 直接在設置 fnContext 之前克隆節(jié)點,最后返回克隆好的 vnode
return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options, renderContext)
} else if (Array.isArray(vnode)) {
var vnodes = normalizeChildren(vnode) || [];
var res = new Array(vnodes.length);
for (var i = 0; i < vnodes.length; i++) {
res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options, renderContext);
}
return res
}
}
// 為了避免復用節(jié)點,fnContext 導致命名槽點不匹配的情況,
// 直接在設置 fnContext 之前克隆節(jié)點,最后返回克隆好的 vnode
function cloneAndMarkFunctionalResult (vnode, data, contextVm, options, renderContext) {
// 在設置fnContext之前克隆節(jié)點,否則,如果重復使用該節(jié)點
// (例如,它來自緩存的正常插槽),fnContext將導致不應匹配的命名插槽。
var clone = cloneVNode(vnode);
clone.fnContext = contextVm;
clone.fnOptions = options;
{
(clone.devtoolsMeta = clone.devtoolsMeta || {}).renderContext = renderContext;
}
if (data.slot) {
(clone.data || (clone.data = {})).slot = data.slot;
}
return clone
}
// 將包含 VNode prop 的多個對象合并為一個單獨的對象;
function mergeProps (to, from) {
for (var key in from) {
to[camelize(key)] = from[key];
}
}
//component初始化和更新的方法,
// 是組件初始化的時候實現的幾個鉤子函數,分別有 init、prepatch、insert、destroy
var componentVNodeHooks = {
// 當 vnode 為 keep-alive 組件時、存在實例且沒被銷毀,為了防止組件流動,
// 直接執(zhí)行了 prepatch。否則直接通過執(zhí)行 createComponentInstanceForVnode
// 創(chuàng)建一個 Component 類型的 vnode 實例,并進行 $mount 操作
init: function init (vnode, hydrating) {
if (
vnode.componentInstance &&
!vnode.componentInstance._isDestroyed &&
vnode.data.keepAlive
) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
componentVNodeHooks.prepatch(mountedNode, mountedNode);
} else {
//根據Vnode生成VueComponent實例
var child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance
);
//將VueComponent實例掛載到dom節(jié)點上,本文是掛載到<my-component></my-component>節(jié)點
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
}
},
// 將已有組件更新成最新的 vnode 上的數據
prepatch: function prepatch (oldVnode, vnode) {
var options = vnode.componentOptions;
var child = vnode.componentInstance = oldVnode.componentInstance;
updateChildComponent(
child,
options.propsData, // 更新props
options.listeners, // 更新listeners
vnode, // 創(chuàng)建父節(jié)點
options.children //創(chuàng)建子節(jié)點
);
},
//insert鉤子函數
insert: function insert (vnode) {
var context = vnode.context;
var componentInstance = vnode.componentInstance;
//判斷組件實例是否已經被mounted,
if (!componentInstance._isMounted) {
// 直接將componentInstance作為參數執(zhí)行mounted鉤子函數
componentInstance._isMounted = true;
callHook(componentInstance, 'mounted');
}
//如果組件為kepp-alive內置組件
if (vnode.data.keepAlive) {
//如果組件已經mounted
if (context._isMounted) {
// 為了防止 keep-alive 子組件更新觸發(fā) activated 鉤子函數,
// 直接就放棄了 walking tree 的更新機制,而是直接將組件實例 componentInstance
// 丟到 activatedChildren 這個數組中
queueActivatedComponent(componentInstance);
} else {
// 否則直接出發(fā)activated鉤子函數進行mounted
activateChildComponent(componentInstance, true);
}
}
},
// 組件銷毀函數
destroy: function destroy (vnode) {
var componentInstance = vnode.componentInstance;
if (!componentInstance._isDestroyed) {
// 如果不是 keep-alive 組件,直接執(zhí)行 $destory 銷毀組件實例,
if (!vnode.data.keepAlive) {
componentInstance.$destroy();
// 否則觸發(fā) deactivated 鉤子函數進行銷毀
} else {
deactivateChildComponent(componentInstance, true /* direct */);
}
}
}
};
var hooksToMerge = Object.keys(componentVNodeHooks);
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (isUndef(Ctor)) {
return
}
var baseCtor = context.$options._base;
// 普通選項對象:將其轉換為構造函數
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor);
}
// 如果在此階段不是構造函數或異步組件工廠則提示
if (typeof Ctor !== 'function') {
{
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// 異步組件
var asyncFactory;
if (isUndef(Ctor.cid)) {
asyncFactory = Ctor;
// 處理了 3 種異步組件的創(chuàng)建方式
Ctor = resolveAsyncComponent(asyncFactory, baseCtor);
if (Ctor === undefined) {
// 異步組件 patch,創(chuàng)建一個注釋節(jié)點作為占位符
return createAsyncPlaceholder(
asyncFactory,
data,
context,
children,
tag
)
}
}
data = data || {};
// 解析constructor上的options屬性
resolveConstructorOptions(Ctor);
//將組件v-modal數據轉換為props和events
if (isDef(data.model)) {
transformModel(Ctor.options, data);
}
//提取props
var propsData = extractPropsFromVNodeData(data, Ctor, tag);
//創(chuàng)建虛擬dom組件
if (isTrue(Ctor.options.functional)) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// 提取偵聽器,因為這些偵聽器需要作為子組件偵聽器而不是DOM偵聽器
var listeners = data.on;
// 替換為帶有.native修飾符的偵聽器,以便在父組件修補程序期間對其進行處理
data.on = data.nativeOn;
if (isTrue(Ctor.options.abstract)) {
// 抽象組件只保留props、偵聽器和插槽
var slot = data.slot;
data = {};
if (slot) {
data.slot = slot;
}
}
// 在占位符節(jié)點上安裝組件管理掛鉤
installComponentHooks(data);
// 返回一個占位符節(jié)點
var name = Ctor.options.name || tag;
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children },
asyncFactory
);
return vnode
}
function createComponentInstanceForVnode (
// 當前組件的vnode
vnode,
// 當前的vue實例 就是div#app,也就是當前組件的父vue實例
parent
) {
// 增加 component 特有options
var options = {
_isComponent: true,
_parentVnode: vnode,// 這里就是站位父VNode,也就是app.vue的占位符
parent: parent// vue實例
};
// 檢查內聯模板渲染函數
var inlineTemplate = vnode.data.inlineTemplate;
if (isDef(inlineTemplate)) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnode.componentOptions.Ctor(options)
}
// 安裝組件鉤子函數,等待patch過程時去執(zhí)行
function installComponentHooks (data) {
var hooks = data.hook || (data.hook = {});
// 遍歷hooksToMerge,不斷向data.hook插入componentVNodeHooks對象中對應的鉤子函數
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var existing = hooks[key];
var toMerge = componentVNodeHooks[key];
if (existing !== toMerge && !(existing && existing._merged)) {
hooks[key] = existing ? mergeHook$1(toMerge, existing) : toMerge;
}
}
}
function mergeHook$1 (f1, f2) {
var merged = function (a, b) {
f1(a, b);
f2(a, b);
};
merged._merged = true;
return merged
}
// 將組件v-modal(值和回調)轉換為prop和event。
function transformModel (options, data) {
// 默認prop是value
var prop = (options.model && options.model.prop) || 'value';
// 默認event是Input
var event = (options.model && options.model.event) || 'input';
// 保存到props屬性中
(data.attrs || (data.attrs = {}))[prop] = data.model.value;
// 將input事件添加到on對象中
var on = data.on || (data.on = {});
var existing = on[event];
var callback = data.model.callback;
if (isDef(existing)) {
if (
Array.isArray(existing)
? existing.indexOf(callback) === -1
: existing !== callback
) {
on[event] = [callback].concat(existing);
}
} else {
on[event] = callback;
}
}
/* */
var SIMPLE_NORMALIZE = 1;
var ALWAYS_NORMALIZE = 2;
// 包裝器函數,用于提供更靈活的接口
function createElement (
context,
tag,
data,
children,
normalizationType,
alwaysNormalize
) {
// 首先檢測data的類型,通過判斷data是不是數組,以及是不是基本類型,來判斷data是否傳入
// 如果傳入,則將所有的參數向前賦值
if (Array.isArray(data) || isPrimitive(data)) {
normalizationType = children;
children = data;
data = undefined;
}
if (isTrue(alwaysNormalize)) {
normalizationType = ALWAYS_NORMALIZE;
}
// 首先判斷data是不是響應式的,vnode中的data不能是響應式的。如果是,則Vue拋出警告
return _createElement(context, tag, data, children, normalizationType)
}
function _createElement (
context,//context表示vnode上上線文環(huán)境
tag,
data,//vnode數據
children,//當前vnode子節(jié)點
normalizationType
) {
// 首先判斷data是不是響應式的,vnode中的data不能是響應式的。如果是,則Vue拋出警告
if (isDef(data) && isDef((data).__ob__)) {
warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
);
return createEmptyVNode()
}
//v-bind中的對象語法
if (isDef(data) && isDef(data.is)) {
tag = data.is;
}
if (!tag) {
// 如果是組件:則設置為falsy值
return createEmptyVNode()
}
// 如果data.key不屬于基本類型,則發(fā)出警告
if (isDef(data) && isDef(data.key) && !isPrimitive(data.key)
) {
{
warn(
'Avoid using non-primitive value as key, ' +
'use string/number value instead.',
context
);
}
}
// 支持單功能子項作為默認作用域插槽
if (Array.isArray(children) &&
typeof children[0] === 'function'
) {
data = data || {};
data.scopedSlots = { default: children[0] };
children.length = 0;
}
// 當alwaysNormalize等于2的時候,調用normalizeChildren去處理children類數組
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children);
// 當alwaysNormalize等于1的時候,調用調用normalizeChildren去處理children類數組
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children);
}
var vnode, ns;
// 判斷tag的類型,如果是string就創(chuàng)建普通dom
if (typeof tag === 'string') {
var Ctor;
ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// 如果存在data.nativeOn并且data.tag不等于component時,發(fā)出警告
if (isDef(data) && isDef(data.nativeOn) && data.tag !== 'component') {
warn(
("The .native modifier for v-on is only valid on components but it was used on <" + tag + ">."),
context
);
}
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
//創(chuàng)建組件
vnode = createComponent(Ctor, data, context, children, tag);
} else {
// 未知或未列出的命名空間元素在運行時檢查,因為當其父元素規(guī)范化子元素時,可能會為其分配命名空間
vnode = new VNode(
tag, data, children,
undefined, undefined, context
);
}
} else {
// 如果不是string就會調用createComponent創(chuàng)建組件
vnode = createComponent(tag, data, context, children);
}
if (Array.isArray(vnode)) {
return vnode
} else if (isDef(vnode)) {
//如果存在vnode和ns,則將ns賦值給vnode.ns
if (isDef(ns)) { applyNS(vnode, ns); }
if (isDef(data)) { registerDeepBindings(data); }
return vnode
} else {
return createEmptyVNode()
}
}
//通過遞歸的方法把ns賦值給vnode.ns
function applyNS (vnode, ns, force) {
vnode.ns = ns;
// 如果vnode.tag等于foreignObject則ns賦值為undefined
if (vnode.tag === 'foreignObject') {
//在foreignObject中使用默認命名空間
ns = undefined;
force = true;
}
//如果vnode有子節(jié)點則進行遞歸循環(huán)
if (isDef(vnode.children)) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
var child = vnode.children[i];
if (isDef(child.tag) && (
isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {
applyNS(child, ns, force);
}
}
}
}
// 確保父級在深度綁定的樣式和類在插槽節(jié)點上使用
function registerDeepBindings (data) {
if (isObject(data.style)) {
//如果有data.style,則調用traverse進行深度監(jiān)聽
traverse(data.style);
}
//如果有data.class,則調用traverse進行深度監(jiān)聽
if (isObject(data.class)) {
traverse(data.class);
}
}
function initRender (vm) {
vm._vnode = null; // 子樹的根
vm._staticTrees = null; // v-once緩存樹
var options = vm.$options;
var parentVnode = vm.$vnode = options._parentVnode; // 父樹中的占位符節(jié)點
var renderContext = parentVnode && parentVnode.context;
vm.$slots = resolveSlots(options._renderChildren, renderContext);
vm.$scopedSlots = emptyObject;
//將createElement fn綁定到此實例
//這樣我們就可以在其中獲得適當的渲染上下文。
//參數順序:標記、數據、子項、規(guī)范化類型、alwaysNormalize
//內部版本由從模板編譯的渲染函數使用
vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); };
// 規(guī)范化始終應用于公共版本,用于用戶編寫的渲染函數。
vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
// $attrs&$listeners已公開,以便更輕松地進行臨時創(chuàng)建。它們需要是反應式的,以便使用它們的HOC始終得到更新
var parentData = parentVnode && parentVnode.data;
{
// Vue的data監(jiān)聽,也是通過defineReactive$$1方法
defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () {
!isUpdatingChildComponent && warn("$attrs is readonly.", vm);
}, true);
defineReactive$$1(vm, '$listeners', options._parentListeners || emptyObject, function () {
!isUpdatingChildComponent && warn("$listeners is readonly.", vm);
}, true);
}
}
var currentRenderingInstance = null;
function renderMixin (Vue) {
// 里面是一些渲染時候的幫助方法,全部掛載到Vue.prototype上,比如創(chuàng)建空節(jié)點、創(chuàng)建文本節(jié)點、toNumber、toString等等
installRenderHelpers(Vue.prototype);
// 使用異步函數來執(zhí)行
Vue.prototype.$nextTick = function (fn) {
return nextTick(fn, this)
};
// 調用render函數
Vue.prototype._render = function () {
var vm = this;
var ref = vm.$options;
var render = ref.render;
var _parentVnode = ref._parentVnode;
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots,
vm.$scopedSlots
);
}
// 設置父vnode。這允許渲染函數具有訪問權限添加到占位符節(jié)點上的數據。
vm.$vnode = _parentVnode;
// render self
var vnode;
try {
// There's no need to maintain a stack because all render fns are called
// separately from one another. Nested component's render fns are called
// when parent component is patched.
currentRenderingInstance = vm;
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
handleError(e, vm, "render");
// 返回錯誤渲染結果,或上一個vnode,以防止渲染錯誤導致空白組件
if (vm.$options.renderError) {
try {
vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e);
} catch (e) {
handleError(e, vm, "renderError");
vnode = vm._vnode;
}
} else {
vnode = vm._vnode;
}
} finally {
currentRenderingInstance = null;
}
// 如果返回的數組只包含一個節(jié)點
if (Array.isArray(vnode) && vnode.length === 1) {
vnode = vnode[0];
}
// 如果渲染函數出錯,則返回空vnode
if (!(vnode instanceof VNode)) {
if (Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
);
}
//給vnode賦值一個空節(jié)點
vnode = createEmptyVNode();
}
//設置父節(jié)點
vnode.parent = _parentVnode;
return vnode
};
}
/* 是為了保證能找到異步組件上定義的組件對象而定義的函數 */
function ensureCtor (comp, base) {
// 如果發(fā)現它是普通對象,則直接通過 Vue.extend 將其轉換成組件的構造函數
if (
comp.__esModule ||
(hasSymbol && comp[Symbol.toStringTag] === 'Module')
) {
comp = comp.default;
}
return isObject(comp)
? base.extend(comp)
: comp
}
// 返回呈現的異步組件的占位符節(jié)點作為注釋節(jié)點,但保留節(jié)點的所有原始信息,這些信息將用于異步服務器渲染和同步
function createAsyncPlaceholder (
factory,
data,
context,
children,
tag
) {
var node = createEmptyVNode();
node.asyncFactory = factory;
node.asyncMeta = { data: data, context: context, children: children, tag: tag };
return node
}
function resolveAsyncComponent (
factory,//factory:異步組件的函數
baseCtor
) {
if (isTrue(factory.error) && isDef(factory.errorComp)) {
return factory.errorComp
}
// 工廠函數異步組件第二次執(zhí)行這里時會返回factory.resolved
if (isDef(factory.resolved)) {
return factory.resolved
}
var owner = currentRenderingInstance;
if (owner && isDef(factory.owners) && factory.owners.indexOf(owner) === -1) {
// already pending
factory.owners.push(owner);
}
if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
return factory.loadingComp
}
if (owner && !isDef(factory.owners)) {
var owners = factory.owners = [owner];
var sync = true;
var timerLoading = null;
var timerTimeout = null;
(owner).$on('hook:destroyed', function () { return remove(owners, owner); });
// 遍歷contexts里的所有元素,依次調用該元素的$forceUpdate()方法 該方法會強制渲染一次
var forceRender = function (renderCompleted) {
for (var i = 0, l = owners.length; i < l; i++) {
(owners[i]).$forceUpdate();
}
if (renderCompleted) {
owners.length = 0;
if (timerLoading !== null) {
clearTimeout(timerLoading);
timerLoading = null;
}
if (timerTimeout !== null) {
clearTimeout(timerTimeout);
timerTimeout = null;
}
}
};
//定義一個resolve函數
var resolve = once(function (res) {
// 緩存解析
factory.resolved = ensureCtor(res, baseCtor);
// 當這不是同步解析時調用回調
if (!sync) {
forceRender(true);
} else {
owners.length = 0;
}
});
//定義一個reject函數
var reject = once(function (reason) {
warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
if (isDef(factory.errorComp)) {
factory.error = true;
forceRender(true);
}
});
//執(zhí)行factory()函數
var res = factory(resolve, reject);
if (isObject(res)) {
if (isPromise(res)) {
// () => Promise
if (isUndef(factory.resolved)) {
res.then(resolve, reject);
}
} else if (isPromise(res.component)) {
res.component.then(resolve, reject);
if (isDef(res.error)) {
factory.errorComp = ensureCtor(res.error, baseCtor);
}
if (isDef(res.loading)) {
factory.loadingComp = ensureCtor(res.loading, baseCtor);
if (res.delay === 0) {
factory.loading = true;
} else {
timerLoading = setTimeout(function () {
timerLoading = null;
if (isUndef(factory.resolved) && isUndef(factory.error)) {
factory.loading = true;
forceRender(false);
}
}, res.delay || 200);
}
}
if (isDef(res.timeout)) {
timerTimeout = setTimeout(function () {
timerTimeout = null;
if (isUndef(factory.resolved)) {
reject(
"timeout (" + (res.timeout) + "ms)"
);
}
}, res.timeout);
}
}
}
sync = false;
// 在同步解決的情況下返回
return factory.loading
? factory.loadingComp
: factory.resolved
}
}
/*獲取第一個組件的子節(jié)點 */
function getFirstComponentChild (children) {
//循環(huán)子節(jié)點,判斷子節(jié)點是否位異步占位符
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) {
return c
}
}
}
}
//初始化事件
function initEvents (vm) {
vm._events = Object.create(null);
vm._hasHookEvent = false;
//初始化父附加事件
var listeners = vm.$options._parentListeners;
if (listeners) {
//修改組件的監(jiān)聽器
updateComponentListeners(vm, listeners);
}
}
var target;
//添加監(jiān)聽事件
function add (event, fn) {
target.$on(event, fn);
}
//移出自定義事件監(jiān)聽器
function remove$1 (event, fn) {
target.$off(event, fn);
}
// 在執(zhí)行完回調之后,移除事件綁定
function createOnceHandler (event, fn) {
var _target = target;
return function onceHandler () {
var res = fn.apply(null, arguments);
if (res !== null) {
_target.$off(event, onceHandler);
}
}
}
//更新組件的監(jiān)聽器
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
// 調用updateListeners來修改監(jiān)聽配置
updateListeners(listeners, oldListeners || {}, add, remove$1, createOnceHandler, vm);
target = undefined;
}
function eventsMixin (Vue) {
var hookRE = /^hook:/;
// 監(jiān)聽事件
Vue.prototype.$on = function (event, fn) {
var vm = this;
//當傳入的監(jiān)聽事件為數組,則循環(huán)遍歷調用$on,否則將監(jiān)聽事件和回調函數添加到事件處理中心_events對象中
if (Array.isArray(event)) {
for (var i = 0, l = event.length; i < l; i++) {
vm.$on(event[i], fn);
}
} else {
// 之前已經有監(jiān)聽event事件,則將此次監(jiān)聽的回調函數添加到其數組中,否則創(chuàng)建一個新數組并添加fn
(vm._events[event] || (vm._events[event] = [])).push(fn);
if (hookRE.test(event)) {
vm._hasHookEvent = true;
}
}
return vm
};
//監(jiān)聽事件,只監(jiān)聽1次, Vue中的事件機制,Vue中的事件機制本身就是一個訂閱-發(fā)布模式的實現
Vue.prototype.$once = function (event, fn) {
var vm = this;
// 定義監(jiān)聽事件的回調函數
function on () {
// 從事件中心移除監(jiān)聽事件的回調函數
vm.$off(event, on);
// 執(zhí)行回調函數
fn.apply(vm, arguments);
}
// 這個賦值是在$off方法里會用到的
// 比如我們調用了vm.$off(fn)來移除fn回調函數,然而我們在調用$once的時候,實際執(zhí)行的是vm.$on(event, on)
// 所以在event的回調函數數組里添加的是on函數,這個時候要移除fn,我們無法在回調函數數組里面找到fn函數移除,只能找到on函數
// 我們可以通過on.fn === fn來判斷這種情況,并在回調函數數組里移除on函數
on.fn = fn;
// 通過$on方法注冊事件,$once最終調用的是$on,并且回調函數是on
vm.$on(event, on);
return vm
};
// 移除自定義事件監(jiān)聽器。
// 如果沒有提供參數,則移除所有的事件監(jiān)聽器;
// 如果只提供了事件,則移除該事件所有的監(jiān)聽器;
// 如果同時提供了事件與回調,則只移除這個回調的監(jiān)聽器。
Vue.prototype.$off = function (event, fn) {
var vm = this;
//調用this.$off()沒有傳參數,則清空事件處理中心緩存的事件及其回調
if (!arguments.length) {
vm._events = Object.create(null);
return vm
}
//當event為數組,則循環(huán)遍歷調用$off,否則將監(jiān)聽事件和回調函數添加到事件處理中心_events對象中
if (Array.isArray(event)) {
for (var i$1 = 0, l = event.length; i$1 < l; i$1++) {
vm.$off(event[i$1], fn);
}
return vm
}
// 獲取當前event里所有的回調函數
var cbs = vm._events[event];
// 如果不存在回調函數,則直接返回,因為沒有可以移除監(jiān)聽的內容
if (!cbs) {
return vm
}
// 如果沒有指定要移除的回調函數,則移除該事件下所有的回調函數
if (!fn) {
vm._events[event] = null;
return vm
}
// 指定了要移除的回調函數
var cb;
var i = cbs.length;
while (i--) {
cb = cbs[i];
// 在事件對應的回調函數數組里面找出要移除的回調函數,并從數組里移除
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1);
break
}
}
return vm
};
// 觸發(fā)事件
Vue.prototype.$emit = function (event) {
var vm = this;
{
var lowerCaseEvent = event.toLowerCase();
if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
tip(
"Event \"" + lowerCaseEvent + "\" is emitted in component " +
(formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " +
"Note that HTML attributes are case-insensitive and you cannot use " +
"v-on to listen to camelCase events when using in-DOM templates. " +
"You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"."
);
}
}
// 觸發(fā)事件對應的回調函數列表
var cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
// $emit方法可以傳參,這些參數會在調用回調函數的時候傳進去
var args = toArray(arguments, 1);
var info = "event handler for \"" + event + "\"";
// 遍歷回調函數列表,調用每個回調函數
for (var i = 0, l = cbs.length; i < l; i++) {
invokeWithErrorHandling(cbs[i], vm, args, vm, info);
}
}
return vm
};
}