简易实现vue diff算法

本文主要介绍了vue的diff的简易实现过程,也就是两个虚拟父节点都是同层级的,且都不包含key属性,当然文章后面也会介绍带有key属性时,diff的计算过程。
如果对简易实现代码的h函数以及mount函数不懂的,可以去看我的另一篇文章:https://www.jianshu.com/p/0cfca7d005cf

vue的diff的简易实现过程(patch函数):

// index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .clickDiv {
      width: 20px;
      height: 20px;
      border: 1px solid #000;
    }
  </style>
</head>
<body>

  <div id="app"></div>

  <script src="./render.js"></script>
  <script>
    let counter = 1
    // compiler编译template后的结果
    const vnode = h("div", {class: 'black'}, [
      h("button", {onclick: function() {counter++; console.log(counter)}} , '+1'),
      h("h2", null, counter)
    ])

    mount(vnode, document.querySelector('#app'))

    setTimeout(() => {
      const vnode1 = h("div", {class: 'black'}, [
        h("div", {onclick: function() {counter--; console.log(counter)}, class: 'clickDiv'} , '-1'),
        h("h2", null, '呵呵呵'),
      ])
      patch(vnode, vnode1)
    }, 2000)
  </script>
</body>
</html>
// h函数的作用就是将compiler编译后的模板转为vnode(也就是js对象)
function h(tag, property, children) {
  return {
    tag,
    property,
    children
  }
}
// 虚拟DOM转为真实DOM
function mount(vnode, container) {
  // 1. 将tag转为标签
  const el = vnode.el = document.createElement(vnode.tag)
  // 2. 给标签设置对应的属性
  if (vnode.property) {
    for (const key in vnode.property) {
      const value = vnode.property[key]
      // 点击事件
      if (key.startsWith("on")) {
        el.addEventListener(key.slice(2), value)
        console.log(el.click)
      } else {
        el.setAttribute(key, value)
      }
    }
  }
  // 3. 处理children
  if (vnode.children) {
    if (typeof vnode.children === 'string' || typeof vnode.children === 'number') {
      el.textContent = vnode.children
    } else {
      vnode.children.forEach(item => {
        mount(item, el)
      });
    }
  }
  // 4. 将节点挂载到父节点上
  container.appendChild(el)
}

// diff算法(最简易实现,同层级,不包含key属性的节点)
// vnode1是oldVNode, vnode2是newVNode
const patch = (vnode1, vnode2) => {
  // 判断是否是同一种标签
  if (vnode1.tag !== vnode2.tag) {
    // 移除oldVNode,添加newVNode
    const elParentEl = vnode1.el.parentElement
    elParentEl.removeChild(vnode1.el)
    mount(vnode2, elParentEl)
  } else {
    // el是引用,在修改el时,同时修改oldVNode,newVNode(目的是:在oldVNode上直接实现DOM更新)
    // el就是最终需要的结果
    const el = vnode2.el = vnode1.el

    // 处理newVNode property(标签的属性),给el添加newVNode的属性
    for (const key in vnode2.property) {
      const newValue = vnode2.property[key]
      const oldValue = vnode1.property[key]
      if (newValue !== oldValue) {
        // 对事件属性做单独处理
        if (key.startsWith("on")) {
          el.addEventListener(key.slice(2), vnode2.property[key])
        } else {
          el.setAttribute(key, newValue)
        }
      }
    }
    // 处理oldVNode property(标签的属性),给el移除oldVNode的属性
    for (const key in vnode1.property) {
      // 对事件属性做单独处理
      if (key.startsWith("on")) {
          el.removeEventListener(key.slice(2), vnode2.property[key])
        } 
      if (!(key in vnode2.property)) {
          el.removeAttribute(key)
      }
    }

    // 处理children
    // 如果newVNode的children是string或者number类型
    if (typeof vnode2.children === 'string' || typeof vnode1.children === 'number') {
      el.innerHTML = vnode2.children
    } else {
      // 如果newVNode的children是array类型
      /**
       * 这儿就实现一种最最简单的情况:
       * vnode不带有key属性
       */
      // newVNode.length = oldVNode.length
      // 对子节点进行diff
      const commonLength = Math.min(vnode1.children.length, vnode2.children.length)
      for (let i = 0; i < commonLength; i++) {
        patch(vnode1.children[i], vnode2.children[i])
      }
      // newVNode.length > oldVNode.length
      // 将newVNode多出来的节点挂载到el上
      if (vnode2.children.length > vnode1.children.length) {
        const newChildren = vnode2.children.slice(commonLength)
        newChildren.forEach(item => {
          mount(item, el)
        })
      }
      // newVNode.length < oldVNode.length
        // 将oldVNode多出来的节点从el上移除
      if (vnode2.children.length < vnode1.children.length) {
        const oldChildren = vnode1.children.slice(commonLength)
        oldChildren.forEach(item => {
          el.remove(item.el)
        })
      }
    }
  }
}

当节点带有key属性时的diff:

新的VNodes和旧的VNodes对比使用diff算法:diff算法中有一个patch函数,用来对比新旧VNode,比较只会在同层级进行, 不会跨层级比较。
A B C D 新
A B F C D 旧
对比过程:
先对新旧VNode长度进行比较,选择较短的VNode进行遍历(while),在遍历过程中,先正序遍历,对相同的节点(patchFlag标记(在编译时加上标记)和有key的情况下)进行比较,然后决定哪些内容进行替换,新增,删除等; 当遇到节点不同时(比如C F),break跳出循环;再进行倒序遍历,内容同正序一样。然后,如果是旧节点多出了VNode就进行unmount(删除)操作,如果是新Vnode多出了就进行mount(新增挂载)操作。如果中间是乱序,则尽可能地在旧的VNode中找到对应的新的VNode,再建立一个数组,然后将旧的Vnode放在与新的Vnode对应的位置上。然后旧的Vnode多余的就进行unmount操作,新的VNode多余的就进行mount操作。
在编译时,会对节点进行加上标记,对于静态节点(简单来说,就是没有变量,不会动态变化的节点)会直接跳过。

如有错误,欢迎指正!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容