首页 > 编程语言 >Vue中的diff算法探析

Vue中的diff算法探析

时间:2023-02-13 16:58:42浏览次数:37  
标签:Vue dom dynamic vnode Indicates 探析 diff 节点

一、什么是diff

 diff 是什么?diff 就是比较两个树,render 会生成两颗树,一个新树 newVnode,一棵旧树oleVnode。然后两棵树进行对比更新差异就是 diff ,全称是 difference, 在 vue 里面diff 算法就是通过 patch 函数来完成的,所有有的时候也叫 patch 算法。

二、diff什么时候会发生

  diff 发生在什么时候?我们可以说是在数据更新的时候发生的 diff ,因为数据更新会运行 render 函数得到虚拟的 dom 树,最后页面重新渲染。

  当组件创建的时候,组件所依赖的属性或者数据发生了改变的时候,会运行一个函数(下面代码中的updateComponent),该函数会做两件事:

  * 运行_render 生成一个新的虚拟 dom 树;

  * 运行 _updata, 传入的_render 生成虚拟的 dom 树,将他和旧的虚拟 dom 树来进行对比,最后完成真实 dom 的更新。

// vue构造函数
function Vue(){
  // ... 其他代码
  var updateComponent = () => {
    this._update(this._render());
  }
  new Watcher(updateComponent);
  // ... 其他代码
}

  _render 函数生成一个新的虚拟的dom 树,然后把他传递到 _update 里面,然后再将 updateComponent 传递给 watcher ,watcher 会监测函数的执行的过程,检测函数执行期间用到了哪些响应式数据并且进行依赖收集,关于watcher可以看https://www.cnblogs.com/zhilili/p/14734468.html

三、_update函数的作用

 

update 函数会接受一个vnode 参数,这是新生成的虚拟 dom 树,同时, _update 函数会通过当前组件的 _vnode 属性,拿到旧的虚拟 dom 树,_update 函数首先会给组件的 _vnode 属性重新赋值,然后让它指向新树。用代码表示如下:

function update(vnode){
  // vnode 新树
  // this._vnode 旧树
  this._vnode=vnode
}

  如果是只是更新虚拟的 dom 树,这样就可以了,但是我们是要更新页面,所以要将 diff 进行树的节点对比,所以可以保存下旧树 oldVnode 来进行对比,用代码表示如下:

<body>
  <div id='app'></div>
  <script src="./vue.js"></script>
  <script>
    const vm=new Vue({
      el:"#app",
    })
    function update(vnode){
      let oldVnode = vm._vnode; // 保存旧树
      this._vnode=vnode // 更新新树
    }
  </script>
</body>

  

四、patch函数的节点对比流程

 

1.根节点进行比较:patch 函数首先对根节点进行比较

 

 

 

如果两个节点【相同】,则进入【更新】流程:

(1)将旧节点的真实 dom 赋值给新节点: newVnode.elm=oldVnode.elm,旧节点会被垃圾回收系机制回收;

(2)对比旧节点和新节点的属性,有变化的更新到真实的 dom 中;

(3)当前新旧两个节点处理完成,开始【对比子节点】

如果两个节点不【相同】:

(1)新节点【递归】,【新建元素】

(2)旧节点【销毁元素】

 

2.对比子节点:虚拟 dom 树已经完成了,就剩修改真实的 dom 了,但是修改真实 dom 的效率是比较耗时的,vue 的原则是能不改就不改,尽量什么也不做,在【对比子节点】时,vue 的一切出发点都是为了:

  * 尽量什么也不做

  * 不行的话,就仅仅修改元素的属性

  * 还不行的话,尽量移动元素,而不是删除和创建元素

  * 实在不行的话,就创建和删除元素

五、Vue2 和 Vue3中的diff算法

Vue2的diff算法

 

 

 

Vue3的diff算法

PatchFlag & ShapeFlag

和vue2不同,vue3的diff不止发生在runtime阶段。在compile阶段,vue会对vnode打上tag,用于patch时的优化。有2种tag:

  • PatchFlag: 用于标示VNode哪里有动态信息
export declare const enum PatchFlags {
    /**
     * Indicates an element with dynamic textContent (children fast path)
     */
    TEXT = 1,
    /**
     * Indicates an element with dynamic class binding.
     */
    CLASS = 2,
    /**
     * Indicates an element with dynamic style
     * The compiler pre-compiles static string styles into static objects
     * + detects and hoists inline static objects
     * e.g. `style="color: red"` and `:style="{ color: 'red' }"` both get hoisted
     * as:
     * ```js
     * const style = { color: 'red' }
     * render() { return e('div', { style }) }
     * ```
     */
    STYLE = 4,
    /**
     * Indicates an element that has non-class/style dynamic props.
     * Can also be on a component that has any dynamic props (includes
     * class/style). when this flag is present, the vnode also has a dynamicProps
     * array that contains the keys of the props that may change so the runtime
     * can diff them faster (without having to worry about removed props)
     */
    PROPS = 8,
    /**
     * Indicates an element with props with dynamic keys. When keys change, a full
     * diff is always needed to remove the old key. This flag is mutually
     * exclusive with CLASS, STYLE and PROPS.
     */
    FULL_PROPS = 16,
    /**
     * Indicates an element with event listeners (which need to be attached
     * during hydration)
     */
    HYDRATE_EVENTS = 32,
    /**
     * Indicates a fragment whose children order doesn't change.
     */
    STABLE_FRAGMENT = 64,
    /**
     * Indicates a fragment with keyed or partially keyed children
     */
    KEYED_FRAGMENT = 128,
    /**
     * Indicates a fragment with unkeyed children.
     */
    UNKEYED_FRAGMENT = 256,
    /**
     * Indicates an element that only needs non-props patching, e.g. ref or
     * directives (onVnodeXXX hooks). since every patched vnode checks for refs
     * and onVnodeXXX hooks, it simply marks the vnode so that a parent block
     * will track it.
     */
    NEED_PATCH = 512,
    /**
     * Indicates a component with dynamic slots (e.g. slot that references a v-for
     * iterated value, or dynamic slot names).
     * Components with this flag are always force updated.
     */
    DYNAMIC_SLOTS = 1024,
    /**
     * Indicates a fragment that was created only because the user has placed
     * comments at the root level of a template. This is a dev-only flag since
     * comments are stripped in production.
     */
    DEV_ROOT_FRAGMENT = 2048,
    /**
     * SPECIAL FLAGS -------------------------------------------------------------
     * Special flags are negative integers. They are never matched against using
     * bitwise operators (bitwise matching should only happen in branches where
     * patchFlag > 0), and are mutually exclusive. When checking for a special
     * flag, simply check patchFlag === FLAG.
     */
    /**
     * Indicates a hoisted static vnode. This is a hint for hydration to skip
     * the entire sub tree since static content never needs to be updated.
     */
    HOISTED = -1,
    /**
     * A special flag that indicates that the diffing algorithm should bail out
     * of optimized mode. For example, on block fragments created by renderSlot()
     * when encountering non-compiler generated slots (i.e. manually written
     * render functions, which should always be fully diffed)
     * OR manually cloneVNodes
     */
    BAIL = -2
}
  • ShapeFlag:用于标示组件的类型
export declare const enum ShapeFlags {
    ELEMENT = 1,
    FUNCTIONAL_COMPONENT = 2,
    STATEFUL_COMPONENT = 4,
    TEXT_CHILDREN = 8,
    ARRAY_CHILDREN = 16,
    SLOTS_CHILDREN = 32,
    TELEPORT = 64,
    SUSPENSE = 128,
    COMPONENT_SHOULD_KEEP_ALIVE = 256,
    COMPONENT_KEPT_ALIVE = 512,
    COMPONENT = 6
}

 

标签:Vue,dom,dynamic,vnode,Indicates,探析,diff,节点
From: https://www.cnblogs.com/web-yj/p/17116673.html

相关文章

  • node版本问题运行vue项目报错
    今天在新电脑安装的node,准备跑vue项目时,居然报错了。因为是在新的设备上安装,所以默认选择官网中的最新稳定版(https://nodejs.org/en/) 然后启动vue 报错!!!  大概......
  • 【VUE】 文件预览
    【VUE】文件预览上传前预览word文档:docx、doc核心代码import{renderAsync}from"docx-preview";/***渲染docx*@parambuffer*/docxRender(buffer){l......
  • vue文件中.env xxx 文件的作用
    .env文件配置Vue项目中,.env文件是运行项目时的环境配置文件。但是在实际开发过程中,有本地开发环境、测试环境、生产环境等,不同环境对应的配置会不一样。因此,需要通过不......
  • Vue使用i18n
    Vue与vue-i18n包安装npmivue-i18n@8Vue2使用8版本Vue3使用默认版本资源准备新建文件夹lang存放使用的语言文件目录结构scrlangen.jszh.jsindex.js......
  • Vue接口地址管理
     项目中有些时候会调用不同的的环境接口地址,统一进行管理便于切换1.static文件夹下新建config.js:(static/目录下的文件并不会被Webpack处理:它们会直接被复制到最终......
  • 禁用vue.js <template>中段落的eslint规则最大行长度
    禁用vue.js<template>中段落的eslint规则最大行长度使用eslint,后配置了extends:[//这个破玩意,好讨厌,配置了这个后,template属性多余2个就开始换行......
  • Vue的computed和watch的区别是什么?
    一、computed介绍computed用来监控自己定义的变量,该变量在data内没有声明,直接在computed里面定义,页面上可直接使用。//基础使用{{msg}}<inputv-model="name"/>......
  • 百度前端常考vue面试题(附答案)
    怎么实现路由懒加载呢这是一道应用题。当打包应用时,JavaScript包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问时才加......
  • Vue.$nextTick的原理是什么-vue面试进阶
    原理性的东西就会文字较多,请耐下心来,细细品味Vue中DOM更新机制当你气势汹汹地使用Vue大展宏图的时候,突然发现,咦,我明明对这个数据进行更改了,但是当我获取它的时候怎么是上......
  • 高级前端二面vue面试题(持续更新中)
    action与mutation的区别mutation是同步更新,$watch严格模式下会报错action是异步操作,可以获取数据后调用mutation提交最终数据MVVM的优缺点?优点:分离......