如有理解不到位的地方 欢迎指正
前置步骤
render.js,
1: 执行render方法,生成虚拟节点传给了lifeCycle中的update方法
vnode = render.call(vm._renderProxy, vm.$createElement)
2:在lifecycle.js文件中
prevVnode保存上次保留的vm._vnode,第一次渲染的时候不存在就去调用vm.patch(vm.$el, vnode, hydrating, false /* removeOnly */)初始化,
后续有prevVnode就走vm.patch(prevVnode, vnode)去做更新(做diff)
export function lifecycleMixin (Vue: Class) {
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
const vm: Component = this
const prevEl = vm.$el
const prevVnode = vm._vnode // 第一次渲染 prevVnode不存在的
const restoreActiveInstance = setActiveInstance(vm)
vm._vnode = vnode // 首次渲染 会把vnode挂载到vm._vnode上
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render patch方法 做的是初始化渲染逻辑
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode)
}
}
//.....
}
正式进入比对流程
源码都在目录下: vdom/patch.js
(如果是真实的节点 并把内容塞到老的后边一个,删除老的)patch➡
(是相同根节点进入儿子情况的判断)➡patchVnode➡
(如果两个节点都有儿子)➡updateChildren
1:在createPatchFunction方法中return了一个patch方法
return function patch (oldVnode, vnode, hydrating, removeOnly) {
// 如果传入 patch(oldVnode,null); 进行卸载
if (isUndef(vnode)) {
if (isDef(oldVnode)) invokeDestroyHook(oldVnode)
return
}
let isInitialPatch = false
const insertedVnodeQueue = []
if (isUndef(oldVnode)) { // patch(vnode); // 组件的挂载 只传一个参数
// empty mount (likely as component), create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
const isRealElement = isDef(oldVnode.nodeType)
//不是真实元素并且是相同节点 比较儿子的情况 (insertedVnodeQueue是做生命周期的)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node 核心:两个节点的比较
patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly)
} else {
//如果是真实元素
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
oldVnode.removeAttribute(SSR_ATTR)
hydrating = true
}
if (isTrue(hydrating)) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
', or missing
. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode)
}
// replacing existing element
const oldElm = oldVnode.elm
const parentElm = nodeOps.parentNode(oldElm)
//根据虚拟节点创造新的节点 并把内容塞到老的后边一个
// create new node
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm,
nodeOps.nextSibling(oldElm)
)
//递归更新节点
// update parent placeholder node element, recursively
if (isDef(vnode.parent)) {
let ancestor = vnode.parent
const patchable = isPatchable(vnode)
while (ancestor) {
for (let i = 0; i < cbs.destroy.length; ++i) {
cbs.destroy[i](ancestor)
}
ancestor.elm = vnode.elm
if (patchable) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, ancestor)
}
// #6513
// invoke insert hooks that may have been merged by create hooks.
// e.g. for directives that uses the "inserted" hook.
const insert = ancestor.data.hook.insert
if (insert.merged) {
// start at index 1 to avoid re-invoking component mounted hook
for (let i = 1; i < insert.fns.length; i++) {
insert.fns[i]()
}
}
} else {
registerRef(ancestor)
}
ancestor = ancestor.parent
}
}
// destroy old node
if (isDef(parentElm)) {
//删除老的节点
removeVnodes([oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
return vnode.elm
}
- 2 核心在于新老的节点都有儿子,进行儿子的比较 updateChildren
function patchVnode (
oldVnode,
vnode,
insertedVnodeQueue,
ownerArray,
index,
removeOnly
) {
if (oldVnode === vnode) { // 新的和老的一样 就不用比对了 基本上不会出现
return
}
if (isDef(vnode.elm) && isDef(ownerArray)) {
// clone reused vnode 虚拟节点copy 使用
vnode = ownerArray[index] = cloneVNode(vnode)
}
const elm = vnode.elm = oldVnode.elm // 两个节点一样 节点的拷贝
if (isTrue(oldVnode.isAsyncPlaceholder)) {//是不是异步组件占位符
if (isDef(vnode.asyncFactory.resolved)) {
hydrate(oldVnode.elm, vnode, insertedVnodeQueue)
} else {
vnode.isAsyncPlaceholder = true
}
return
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (isTrue(vnode.isStatic) &&
isTrue(oldVnode.isStatic) &&
vnode.key === oldVnode.key &&
(isTrue(vnode.isCloned) || isTrue(vnode.isOnce))
) {
vnode.componentInstance = oldVnode.componentInstance
return
}
let i
const data = vnode.data
//组件的更新流程
if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {
i(oldVnode, vnode)
}
//复用完节点
const oldCh = oldVnode.children // 老儿子
const ch = vnode.children // 新的儿子
if (isDef(data) && isPatchable(vnode)) {
// 调用更新逻辑 包含 当前样式更新, 指令的更新
// cb以此调用比对方法,更新逻辑在运行时platform/modules下边的属性类等的比对方法
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
if (isDef(i = data.hook) && isDef(i = i.update)) i(oldVnode, vnode)
}
if (isUndef(vnode.text)) { // 如果不是文本 并且两个人都有内容
if (isDef(oldCh) && isDef(ch)) { // 两个儿子的比对
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
} else if (isDef(ch)) { // 新的有儿子 那么老的就没儿子
if (process.env.NODE_ENV !== 'production') {
checkDuplicateKeys(ch)
}
// 将文本清空 添加新儿子
if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
// 添加儿子
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
} else if (isDef(oldCh)) { // 如果老的有儿子 ,新的没儿子
removeVnodes(oldCh, 0, oldCh.length - 1) // 删除老儿子
} else if (isDef(oldVnode.text)) { //老的是文本清空
nodeOps.setTextContent(elm, '')
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text) // 更新文本内容
}
if (isDef(data)) { // 如果是组件 会去调用组件的postpatch 方法
if (isDef(i = data.hook) && isDef(i = i.postpatch)) i(oldVnode, vnode)
}
}
- 3 diff双指针比较
首先是特殊情况头头比对;尾尾对比;头尾对比:并且把相同的节点移动到右边;尾头对比:并且把相同的移动到左边
最后乱序比对,对比到相同的移动,并且原来的位置重置为undefined(否则会造成数组塌陷)
//核心 双指针比较
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
let oldStartIdx = 0
let newStartIdx = 0
let oldEndIdx = oldCh.length - 1
let oldStartVnode = oldCh[0]
let oldEndVnode = oldCh[oldEndIdx]
let newEndIdx = newCh.length - 1
let newStartVnode = newCh[0]
let newEndVnode = newCh[newEndIdx]
let oldKeyToIdx, idxInOld, vnodeToMove, refElm
// removeOnly is a special flag used only by
// to ensure removed elements stay in correct relative positions
// during leaving transitions
const canMove = !removeOnly
if (process.env.NODE_ENV !== 'production') {
checkDuplicateKeys(newCh)
}
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx]
} else if (sameVnode(oldStartVnode, newStartVnode)) { // 头头比对
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
oldStartVnode = oldCh[++oldStartIdx]
newStartVnode = newCh[++newStartIdx]
} else if (sameVnode(oldEndVnode, newEndVnode)) { // 尾尾比对
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
oldEndVnode = oldCh[--oldEndIdx]
newEndVnode = newCh[--newEndIdx]
// ABCD
// BCDA
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right 头尾比对
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
oldStartVnode = oldCh[++oldStartIdx]
newEndVnode = newCh[--newEndIdx]
// ABCD
// DABC
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
oldEndVnode = oldCh[--oldEndIdx]
newStartVnode = newCh[++newStartIdx]
} else {
// 乱序比对
// 先创建索引
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
idxInOld = isDef(newStartVnode.key)
? oldKeyToIdx[newStartVnode.key]
: findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx)
if (isUndef(idxInOld)) { // New element 新创建塞入
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx)
} else {
vnodeToMove = oldCh[idxInOld]
//判断是不是相同节点
if (sameVnode(vnodeToMove, newStartVnode)) {
//相同 比对 并且移动和插入 置空
patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
oldCh[idxInOld] = undefined // 做一个占位符
canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm)
} else {
// 如果key一样 标签不一样也是一个新元素
// same key but different element. treat as new element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx)
}
}
//不同移动新的节点
newStartVnode = newCh[++newStartIdx] // 不停的移动新的节点
}
}
//
if (oldStartIdx > oldEndIdx) {
refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm
addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
} else if (newStartIdx > newEndIdx) {
//老的多
removeVnodes(oldCh, oldStartIdx, oldEndIdx)
}
}