美文网首页
vue虚拟DOM初探

vue虚拟DOM初探

作者: 梦行乌托邦 | 来源:发表于2020-07-15 00:10 被阅读0次

    vue源码版本:2.6.11
    虚拟DOM
    src/core/vdom/vnode.js

    export default class VNode {
      tag: string | void;
      data: VNodeData | void;
      children: ?Array<VNode>;
      text: string | void;
      elm: Node | void;
      ns: string | void;
      context: Component | void; // rendered in this component's scope
      key: string | number | void;
      componentOptions: VNodeComponentOptions | void;
      componentInstance: Component | void; // component instance
      parent: VNode | void; // component placeholder node
    
      // strictly internal
      raw: boolean; // contains raw HTML? (server only)
      isStatic: boolean; // hoisted static node
      isRootInsert: boolean; // necessary for enter transition check
      isComment: boolean; // empty comment placeholder?
      isCloned: boolean; // is a cloned node?
      isOnce: boolean; // is a v-once node?
      asyncFactory: Function | void; // async component factory function
      asyncMeta: Object | void;
      isAsyncPlaceholder: boolean;
      ssrContext: Object | void;
      fnContext: Component | void; // real context vm for functional nodes
      fnOptions: ?ComponentOptions; // for SSR caching
      devtoolsMeta: ?Object; // used to store functional render context for devtools
      fnScopeId: ?string; // functional scope id support
    
      constructor (
        tag?: string,
        data?: VNodeData,
        children?: ?Array<VNode>,
        text?: string,
        elm?: Node,
        context?: Component,
        componentOptions?: VNodeComponentOptions,
        asyncFactory?: Function
      ) {
        this.tag = tag
        this.data = data
        this.children = children
        this.text = text
        this.elm = elm
        this.ns = undefined
        this.context = context
        this.fnContext = undefined
        this.fnOptions = undefined
        this.fnScopeId = undefined
        this.key = data && data.key
        this.componentOptions = componentOptions
        this.componentInstance = undefined
        this.parent = undefined
        this.raw = false
        this.isStatic = false
        this.isRootInsert = true
        this.isComment = false
        this.isCloned = false
        this.isOnce = false
        this.asyncFactory = asyncFactory
        this.asyncMeta = undefined
        this.isAsyncPlaceholder = false
      }
    
      // DEPRECATED: alias for componentInstance for backwards compat.
      /* istanbul ignore next */
      get child (): Component | void {
        return this.componentInstance
      }
    }
    

    虚拟DOM(Virtual DOM)是对DOM的JS抽象表示,它们是JS对象,能够描述DOM结构和关系。

    虚拟DOM轻量、快速,当它们发生变化时通过新旧虚拟DOM对比可以得到最小DOM操作量,从而提升性能和用户体验。本质上是使用JS运算成本替换DOM操作的执行成本。

    vdom树首页生成、渲染发生在
    mountComponent(src/core/instance/lifysysle.js),这个是在Vue.prototype.$mount中调用的。

    img1
    看以下源码注释哦
    export function mountComponent (
      vm: Component,
      el: ?Element,
      hydrating?: boolean
    ): Component {
      vm.$el = el // 将el存放到vue的组件实例vm上
    
      // 拿出render
      if (!vm.$options.render) { // 生成render
        vm.$options.render = createEmptyVNode
        if (process.env.NODE_ENV !== 'production') {
         ...
        }
      }
      callHook(vm, 'beforeMount')
    
      // 定义了更新函数
      let updateComponent
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        ...
      } else {
        updateComponent = () => {
          // 首先执行render()返回vnode
          // 然后vnode作为参数执行update做dom更新
          vm._update(vm._render(), hydrating)
        }
      }
    
      // we set this to vm._watcher inside the watcher's constructor
      // since the watcher's initial patch may call $forceUpdate (e.g. inside child
      // component's mounted hook), which relies on vm._watcher being already defined
      // 创建一个组件相关的watcher实例
      //  一个组件一个watcher实例,$watcher/watcher选项会额外创建 
      new Watcher(vm, updateComponent, noop, {
        before () {
          if (vm._isMounted && !vm._isDestroyed) {
            callHook(vm, 'beforeUpdate')
          }
        }
      }, true /* isRenderWatcher */)
      hydrating = false
    
      // manually mounted instance, call mounted on self
      // mounted is called for render-created child components in its inserted hook
      if (vm.$vnode == null) {
        vm._isMounted = true
        callHook(vm, 'mounted')
      }
      return vm
    }
    

    找到mountComponent中调用的vm._render()代码
    src/core/instance/render.js

    export function renderMixin (Vue: Class<Component>) {
     ...
      Vue.prototype._render = function (): VNode {
        const vm: Component = this
        // 拿到render
        const { render, _parentVnode } = vm.$options
    
       ...
        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)
          ...
        return vnode
      }
    }
    

    找到mountComponent中调用的vm._update()代码
    src/core/instance/lifecycle.js

    export function lifecycleMixin (Vue: Class<Component>) {
      Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
        const vm: Component = this
        const prevEl = vm.$el // 之前的dom
        const prevVnode = vm._vnode // 之前的vnode
        const restoreActiveInstance = setActiveInstance(vm)
        vm._vnode = vnode // 新的vnode
        // Vue.prototype.__patch__ is injected in entry points
        // based on the rendering backend used.
        if (!prevVnode) { 
           // 如果没有老的vnode,说明在初始化
          // initial render
          vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
        } else {
           // 更新周期直接diff,返回新的dom
          // updates
          vm.$el = vm.__patch__(prevVnode, vnode)
        }
       ...
      }
      ...
    }
    

    找到以上_update调用的vm.patch
    src/platforms/web/runtime/index.js

    // install platform patch function
    Vue.prototype.__patch__ = inBrowser ? patch : noop
    

    patch定义在src/platforms/web/runtime/patch.js

    // 扩展操作:把通用模块和浏览器中特有的合并
    const modules = platformModules.concat(baseModules)
    // 工厂函数:创建浏览器特有的patch函数,这里主要解决跨平台问题
    // nodeOps提供一些真实的DOM操作
    export const patch: Function = createPatchFunction({ nodeOps, modules })
    

    createPatchFunction定义在src/core/vdom/patch.js

    export function createPatchFunction (backend) {
      let i, j
      const cbs = {}
    
      const { modules, nodeOps } = backend
    
      for (i = 0; i < hooks.length; ++i) {
        cbs[hooks[i]] = []
        for (j = 0; j < modules.length; ++j) {
          if (isDef(modules[j][hooks[i]])) {
            cbs[hooks[i]].push(modules[j][hooks[i]])
          }
        }
      }
      ...
      // 这里返回了浏览器中使用的patch方法
      return function patch (oldVnode, vnode, hydrating, removeOnly) {
        if (isUndef(vnode)) { // 新vnode不存在:删除
          if (isDef(oldVnode)) invokeDestroyHook(oldVnode)
          return
        }
    
        let isInitialPatch = false
        const insertedVnodeQueue = []
    
        // old不存在:新增
        if (isUndef(oldVnode)) {
          // empty mount (likely as component), create new root element
          isInitialPatch = true
          createElm(vnode, insertedVnodeQueue)
        } else { // 改!!!
         // old如果拥有nodeType,则是一个dom
          const isRealElement = isDef(oldVnode.nodeType)
          if (!isRealElement && sameVnode(oldVnode, vnode)) {
            // patch existing root node
            // 自定义组件补丁操作 
            patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly)
          } else {
           //  传入的是dom
            if (isRealElement) { // 以下主要是服务端渲染相关的代码
             ...
            }
    
            // replacing existing element
            // 为什么替换已存在元素?
            const oldElm = oldVnode.elm
            const parentElm = nodeOps.parentNode(oldElm)
    
            // create new node
            // 将虚拟节点转换为真实dom节点
            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)
            )
    
           ...
    
            // destroy old node
            if (isDef(parentElm)) {
              removeVnodes([oldVnode], 0, 0)
            } else if (isDef(oldVnode.tag)) {
              invokeDestroyHook(oldVnode)
            }
          }
        }
    
        invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
        return vnode.elm
      }
    }
    

    vue中的patching算法

    • 两棵树进行比较,只比较同层。
    • 同层级只做三件事:增删改。new vNode不存在就删;old VNode不存在就增;都存在就比较类型,类型不同直接替换,类型相同执行更新

    找到以上patchVnode定义的地方(同文件)

    function patchVnode (
        oldVnode,
        vnode,
        insertedVnodeQueue,
        ownerArray,
        index,
        removeOnly
      ) {
      ...
        // 异步组件处理
        if (isTrue(oldVnode.isAsyncPlaceholder)) {
          ...
        }
    
        // 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.
    // 静态节点可复用,更新componentInstance跳过
        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)) {
          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)) {
          // 新老都有children
          if (isDef(oldCh) && isDef(ch)) {
            // 新老children不一样
            if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
          } else if (isDef(ch)) { // 只有新的有children
           ...
            // 往老里面加东西
            if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
            addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
          } else if (isDef(oldCh)) { // 只有老的有children
            // 删除旧内容
            removeVnodes(oldCh, 0, oldCh.length - 1)
          } else if (isDef(oldVnode.text)) {
            // 新的没文本老的有文本,清空
            nodeOps.setTextContent(elm, '')
          }
        } else if (oldVnode.text !== vnode.text) {
          // 新老都没有children,新老的文本内容不一样
          nodeOps.setTextContent(elm, vnode.text)
        }
        // 钩子
        if (isDef(data)) {
          if (isDef(i = data.hook) && isDef(i = i.postpatch)) i(oldVnode, vnode)
        }
      }
    

    patchVnode

    1. 如果新旧VNode都是静态的,同时它们的key相同(代表同⼀节点),并且新的VNode是clone或 者是标记了v-once,那么只需要替换elm以及componentInstance即可。
    2. 新⽼节点均有children⼦节点,则对子节点进行diff操作,调用updateChildren,这个 updateChildren也是diff的核心。
    3. 如果⽼节点没有子节点⽽新节点存在子节点,先清空老节点DOM的⽂本内容,然后为当前DOM节点加⼊⼦节点。
    4. 当新节点没有子节点⽽⽼节点有子节点的时候,则移除该DOM节点的所有⼦节点。
    5. 当新老节点都⽆子节点的时候,只是⽂文本的替换。

    找到以上updateChildren定义的地方(同文件)

    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 <transition-group>
        // 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)) { // 规则1
            patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
            oldStartVnode = oldCh[++oldStartIdx]
            newStartVnode = newCh[++newStartIdx]
          } else if (sameVnode(oldEndVnode, newEndVnode)) { // 规则1
            patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
            oldEndVnode = oldCh[--oldEndIdx]
            newEndVnode = newCh[--newEndIdx]
          } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
    // 规则2
            patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
            canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
            oldStartVnode = oldCh[++oldStartIdx]
            newEndVnode = newCh[--newEndIdx]
          } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
    // 规则3
            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 {
                // same key but different element. treat as new element
                createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx)
              }
            }
            newStartVnode = newCh[++newStartIdx]
          }
        }
        // 规则6
        if (oldStartIdx > oldEndIdx) {
          refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm
          addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
        } else if (newStartIdx > newEndIdx) { // 规则7
          removeVnodes(oldCh, oldStartIdx, oldEndIdx)
        }
      }
    
    img1

    updateChildren

    • 首尾设置两个游标
    • oldStartVnode、oldEndVnode与newStartVnode、newEndVnode两两交叉比较,共有4种⽐较方法。
    • 规则1:当 oldStartVnode和newStartVnode 或者 oldEndVnode和newEndVnode 满足sameVnode,直接将该 VNode节点进行patchVnode即可,不需再遍历就完成了⼀次循环。
    • 规则2:如果oldStartVnode与newEndVnode满⾜sameVnode。说明oldStartVnode已经跑到了oldEndVnode 后⾯去了,进⾏patchVnode的同时还需要将真实DOM节点移动到oldEndVnode的后⾯。
    • 规则3:如果oldEndVnode与newStartVnode满足sameVnode,说明oldEndVnode跑到了oldStartVnode的前面,进⾏patchVnode的同时要将oldEndVnode对应DOM移动到oldStartVnode对应DOM的前面。
    • 规则4:如果以上情况均不不符合,则在old VNode中找与newStartVnode满足sameVnode的vnodeToMove,若存在执行patchVnode,同时将vnodeToMove对应DOM移动到oldStartVnode对应的DOM的前面。
    • 规则5: 当然也有可能newStartVnode在old VNode节点中找不到⼀致的key,或者是即便key相同却不不是 sameVnode,这个时候会调用createElm创建⼀个新的DOM节点。
    • 规则6:当结束时oldStartIdx > oldEndIdx,这个时候旧的VNode节点已经遍历完了,但是新的节点还没有。说 明了新的VNode节点实际上⽐老的VNode节点多,需要将剩下的VNode对应的DOM插入到真实DOM 中,此时调⽤addVnodes(批量调⽤createElm接⼝)。
    • 规则7:但是,当结束时newStartIdx > newEndIdx时,说明新的VNode节点已经遍历完了,但是老的节点还有剩余,需要从⽂档中删除节点。

    相关文章

      网友评论

          本文标题:vue虚拟DOM初探

          本文链接:https://www.haomeiwen.com/subject/lxxqhktx.html