Vue源码解读(六):update和patch

2023-11-09

Vue 的 _update 是实例上的一个私有方法,主要的作用就是把 VNode 渲染成真实的 DOM ,它在首次渲染和数据更新的时候被调用。在数据更新的时候会发生新 VNode 和 旧 VNode 对比,获取差异更新视图,我们常说的 diff 就是发生在此过程中。

_update

// src/core/instance/lifecycle.js
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
  const vm: Component = this
  // 页面的挂载点,真实的元素
  const prevEl = vm.$el
  // 老 VNode
  const prevVnode = vm._vnode
  const restoreActiveInstance = setActiveInstance(vm)
  // 新 VNode
  vm._vnode = vnode
  // Vue.prototype.__patch__ is injected in entry points
  // based on the rendering backend used.
  if (!prevVnode) {
    // 老 VNode 不存在,表示首次渲染,即初始化页面时走这里
    vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
  } else {
    // 响应式数据更新时,即更新页面时走这里
    vm.$el = vm.__patch__(prevVnode, vnode)
  }
  restoreActiveInstance()
  // update __vue__ reference
  if (prevEl) {
    prevEl.__vue__ = null
  }
  if (vm.$el) {
    vm.$el.__vue__ = vm
  }
  // if parent is an HOC, update its $el as well
  if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
    vm.$parent.$el = vm.$el
  }
  // updated hook is called by the scheduler to ensure that children are
  // updated in a parent's updated hook.
}

__patch__

// src/platforms/web/runtime/index.js
//  web 平台的 patch 函数,不同平台的定义不相同。
Vue.prototype.__patch__ = inBrowser ? patch : noop

patch

// src/platforms/web/runtime/patch.js
import * as nodeOps from 'web/runtime/node-ops'
import { createPatchFunction } from 'core/vdom/patch'
import baseModules from 'core/vdom/modules/index'
import platformModules from 'web/runtime/modules/index'

// the directive module should be applied last, after all
// built-in modules have been applied.
const modules = platformModules.concat(baseModules)

// 传入平台特有的一些操作,然后返回一个 patch 函数
export const patch: Function = createPatchFunction({ nodeOps, modules })

patchcreatePatchFunction 的返回值,这里传入了一个对象,nodeOps 封装了一系列相关平台 DOM的一些操作方法,modules 表示平台特有的一些操作,比如:attr、class、style、event 等,还有核心的 directive 和 ref,它们会向外暴露一些特有的方法。这里不做详细介绍了,有兴趣的老铁可以去了解了解。

createPatchFunction

// src/core/vdom/patch.js
const hooks = ['create', 'activate', 'update', 'remove', 'destroy']
/**
 * 传入相关平台一些功能操作,最后返回 patch 函数
 */
export function createPatchFunction (backend) {
  let i, j
  const cbs = {}

  const { modules, nodeOps } = backend
  /**
   * hooks = ['create', 'activate', 'update', 'remove', 'destroy']
   * 遍历这些钩子,然后从 modules 的各个模块中找到相应的方法,比如:directives 中的 create、update、destroy 方法
   *  cbs[hook] = [hook 方法],比如: cbs.create = [fn1, fn2, ...]
   */
  for (i = 0; i < hooks.length; ++i) {
    // 比如 cbs.create = []
    cbs[hooks[i]] = []
    for (j = 0; j < modules.length; ++j) {
      if (isDef(modules[j][hooks[i]])) {
        // 遍历各个 modules,找出各个 module 中的 create 方法,然后添加到 cbs.create 数组中
        cbs[hooks[i]].push(modules[j][hooks[i]])
      }
    }
  }
  
  /**
   * ...这里定义了一大堆辅助函数,下面用到了捡重点看一下,不一一描述了。
   */
  
  /**
   * @param oldVnode  旧节点,可以不存在或是一个 DOM 对象
   * @param vnode  新节点,_render 返回的节点
   * @param hydrating  是否是服务端渲染
   * @param removeOnly  是给 transition-group 用的
   */
  return function patch (oldVnode, vnode, hydrating, removeOnly) {
    // 新节点不存在,旧节点存在,表示移除,销毁旧节点。
    if (isUndef(vnode)) {
      if (isDef(oldVnode)) invokeDestroyHook(oldVnode)
      return
    }
    let isInitialPatch = false
    const insertedVnodeQueue = []
    if (isUndef(oldVnode)) {
      // 新节点存在,旧节点不存在,表示新增。
      isInitialPatch = true
      createElm(vnode, insertedVnodeQueue)
    } else {
      // 新旧节点都存在
      
      // 旧节点是否为真实的元素
      const isRealElement = isDef(oldVnode.nodeType)
      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 ' +
                '<p>, or missing <tbody>. Bailing hydration and performing ' +
                'full client-side render.'
              )
            }
          }
          // either not server-rendered, or hydration failed.
          // create an empty node and replace it
          // 不是服务端渲染或服务端渲染失败,把 oldVnode 转换成 VNode 对象.
          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
  }
}

createPatchFunction 返回的 patch 方法来看,主要分为这么几种情况做处理:

  • 新节点不存在,旧节点存在,表示移除
  • 新节点存在,旧节点不存在,表示新增
  • 新旧节点都存在,旧节点不是真实的元素且新旧节点是同一节点,表示 修改(更新)
  • 新旧节点都存在,旧节点是真实的元素,一般是初始化渲染,旧节点的真实 DOM 也就是传入进来的 vm.$el 对应的元素,比如 <div id="app">;这里还有一个情况就是当 vnode.parent 存在,又不是同一节点,表示 替换(更新),比如异步组件。

移除节点

invokeDestroyHook

// src/core/vdom/patch.js
/**
 * 销毁节点:
 *   执行组件的 destroy 钩子,即执行 $destroy 方法 
 *   执行组件各个模块(style、class、directive 等)的 destroy 方法
 *   如果 vnode 还存在子节点,则递归调用 invokeDestroyHook
 */
function invokeDestroyHook (vnode) {
  let i, j
  const data = vnode.data
  if (isDef(data)) {
    if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode)
    for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode)
  }
  if (isDef(i = vnode.children)) {
    for (j = 0; j < vnode.children.length; ++j) {
      invokeDestroyHook(vnode.children[j])
    }
  }
}

初始化

createPatchFunction 中的 patch 方法内,由于传入的 vm.$el,实际上是一个真实的 DOM,所以 isRealElementtrue,(服务端渲染的先跳过)然后通过 emptyNodeAtoldVnode 转换成 VNode 对象。

emptyNodeAt

// src/core/vdom/patch.js
function emptyNodeAt (elm) {
  return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}

createElm

然后调用 createElm 方法,这个是重点:

// src/core/vdom/patch.js
function createElm (
  vnode,
  insertedVnodeQueue,
  parentElm,
  refElm,
  nested,
  ownerArray,
  index
) {
  if (isDef(vnode.elm) && isDef(ownerArray)) {
    // This vnode was used in a previous render!
    // now it's used as a new node, overwriting its elm would cause
    // potential patch errors down the road when it's used as an insertion
    // reference node. Instead, we clone the node on-demand before creating
    // associated DOM element for it.
    vnode = ownerArray[index] = cloneVNode(vnode)
  }
  vnode.isRootInsert = !nested // for transition enter check
  /**
   * 1、如果 vnode 是一个组件,则执行 init 钩子,创建组件实例并挂载,
   * 然后为组件执行各个模块的 create 钩子
   *   如果组件被 keep-alive 包裹,则激活组件
   * 2、如果是一个普通元素,则什么也不做
   */
  if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
    return
  }
  // 获取 Data 对象
  const data = vnode.data
  // 获取子VNode
  const children = vnode.children
  // 判断 tag
  const tag = vnode.tag
  if (isDef(tag)) {
   // 如有有 tag 属性
    if (process.env.NODE_ENV !== 'production') {
      if (data && data.pre) {
        creatingElmInVPre++
      }
       // 未知标签
      if (isUnknownElement(vnode, creatingElmInVPre)) {
        warn(
          'Unknown custom element: <' + tag + '> - did you ' +
          'register the component correctly? For recursive components, ' +
          'make sure to provide the "name" option.',
          vnode.context
        )
      }
    }
    // 创建元素节点
    vnode.elm = vnode.ns
      ? nodeOps.createElementNS(vnode.ns, tag)
      : nodeOps.createElement(tag, vnode)
    setScope(vnode)
    /* istanbul ignore if */
    if (__WEEX__) {
      // in Weex, the default insertion order is parent-first.
      // List items can be optimized to use children-first insertion
      // with append="tree".
      const appendAsTree = isDef(data) && isTrue(data.appendAsTree)
      if (!appendAsTree) {
        if (isDef(data)) {
          invokeCreateHooks(vnode, insertedVnodeQueue)
        }
        insert(parentElm, vnode.elm, refElm)
      }
      createChildren(vnode, children, insertedVnodeQueue)
      if (appendAsTree) {
        if (isDef(data)) {
          invokeCreateHooks(vnode, insertedVnodeQueue)
        }
        insert(parentElm, vnode.elm, refElm)
      }
    } else {
      // 递归创建所有子节点(普通元素、组件)
      createChildren(vnode, children, insertedVnodeQueue)
      if (isDef(data)) {
        invokeCreateHooks(vnode, insertedVnodeQueue)
      }
      // 将节点插入父节点
      insert(parentElm, vnode.elm, refElm)
    }
    if (process.env.NODE_ENV !== 'production' && data && data.pre) {
      creatingElmInVPre--
    }
  } else if (isTrue(vnode.isComment)) {
    // 注释节点,创建注释节点并插入父节点
    vnode.elm = nodeOps.createComment(vnode.text)
    insert(parentElm, vnode.elm, refElm)
  } else {
    // 文本节点,创建文本节点并插入父节点
    vnode.elm = nodeOps.createTextNode(vnode.text)
    insert(parentElm, vnode.elm, refElm)
  }
}

createElm 的作用就是通过 VNode 创建真实的 DOM 插入到父节点中,它首先会执行 createComponent 方法,这个方法是用来创建子组件的,在初始化的时候会返回 false,后面组件新增的时候再看这个方法。然后会对判断 vnode.tag,如果存在的话,会走入下面的逻辑:

vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode)

createElementNS

// src/platforms/web/runtime/node-ops.js
// 创建带命名空间的元素节点
export function createElementNS (namespace: string, tagName: string): Element {
  return document.createElementNS(namespaceMap[namespace], tagName)
}

createElement

// src/platforms/web/runtime/node-ops.js
// 创建标签名为 tagName 的元素节点
export function createElement (tagName: string, vnode: VNode): Element {
  // 创建元素节点
  const elm = document.createElement(tagName)
  if (tagName !== 'select') {
    return elm
  }
  // false or null will remove the attribute but undefined will not
  // 如果是 select 元素,则为它设置 multiple 属性
  if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {
    elm.setAttribute('multiple', 'multiple')
  }
  return elm
}

接着会判断 __WEEX__,这个是 Native 端的,跳过,接着执行 createChildren

createChildren

// src/core/vdom/patch.js
// 创建所有子节点,并将子节点插入父节点,形成一棵 DOM 树
function createChildren (vnode, children, insertedVnodeQueue) {
  if (Array.isArray(children)) {
    // children 是数组,表示是一组节点
    if (process.env.NODE_ENV !== 'production') {
      // 检测这组节点的 key 是否重复
      checkDuplicateKeys(children)
    }
    // 遍历这组节点,依次创建这些节点然后插入父节点,形成一棵 DOM 树
    for (let i = 0; i < children.length; ++i) {
      createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i)
    }
  } else if (isPrimitive(vnode.text)) {
    // 说明是文本节点,创建文本节点,并插入父节点
    nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)))
  }
}

createChildren 实际就是遍历子 VNode,递归调用 createElm,深度优先的遍历算法。这里要注意的一点是在遍历过程中会把 vnode.elm 作为父容器的 DOM 节点占位符传入。

然后调用 invokeCreateHooks :

invokeCreateHooks

// src/core/vdom/patch.js
/**
  * 执行所有的 create 的钩子并把 vnode push 到 insertedVnodeQueue 中
  * 调用各个模块的 create 方法,比如创建属性的、创建样式的、指令的等等
  */
function invokeCreateHooks (vnode, insertedVnodeQueue) {
  for (let i = 0; i < cbs.create.length; ++i) {
    cbs.create[i](emptyNode, vnode)
  }
  i = vnode.data.hook // Reuse variable
  if (isDef(i)) {
    if (isDef(i.create)) i.create(emptyNode, vnode)
    if (isDef(i.insert)) insertedVnodeQueue.push(vnode)
  }
}

最后调用 insert 把 DOM 插入父节点中。

insert

// src/core/vdom/patch.js
// 向父节点插入节点 
function insert (parent, elm, ref) {
  if (isDef(parent)) {
    if (isDef(ref)) {
      if (nodeOps.parentNode(ref) === parent) {
        nodeOps.insertBefore(parent, elm, ref)
      }
    } else {
      nodeOps.appendChild(parent, elm)
    }
  }
}
// src/platforms/web/runtime/node-ops.js
// 在指定节点前插入节点
export function insertBefore (parentNode: Node, newNode: Node, referenceNode: Node) {
  parentNode.insertBefore(newNode, referenceNode)
}
// 添加子节点
export function appendChild (node: Node, child: Node) {
  node.appendChild(child)
}

到这里 createElm 中判断 vnode.tag,如果存在的的逻辑走完了,如果不存在的话,它可能是注释或者纯文本节点。

// src/core/vdom/patch.js
if (isDef(tag)) {
  // ...
} else if (isTrue(vnode.isComment)) {
  // 注释节点,创建注释节点并插入父节点
  vnode.elm = nodeOps.createComment(vnode.text)
  insert(parentElm, vnode.elm, refElm)
} else {
  // 文本节点,创建文本节点并插入父节点
  vnode.elm = nodeOps.createTextNode(vnode.text)
  insert(parentElm, vnode.elm, refElm)
}
// src/platforms/web/runtime/node-ops.js
// 创建注释节点
export function createComment (text: string): Comment {
  return document.createComment(text)
}
// 创建文本节点
export function createTextNode (text: string): Text {
  return document.createTextNode(text)
}

到这里返回的 patch 中的 createElmcreateChildren 会递归创建子节点或组件 )就执行完了。接下来就是移除旧节点了。

// 移除老节点
if (isDef(parentElm)) {
  removeVnodes([oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
  invokeDestroyHook(oldVnode)
}

在初始化 _update 执行完,调用 mounted 声明周期钩子,初始化执行完毕

// src/core/instance/lifecycle.js
export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  // ...
  updateComponent = () => {
    vm._update(vm._render(), hydrating)
  }
  // vm.$vnode 表示 Vue 实例的父虚拟 Node,所以它为 Null 则表示当前是根 Vue 的实例
  if (vm.$vnode == null) {
    vm._isMounted = true
    callHook(vm, 'mounted')
  }
  return vm
}

新增

当新节点存在,旧节点不存在的时候,表示新增。在上面初始化说到 createChildren 方法会对子节点循环调用 createElm。当 createElm 遇到组件时的处理方式:

createElm

// src/core/vdom/patch.js
function createElm (
  vnode,
  insertedVnodeQueue,
  parentElm,
  refElm,
  nested,
  ownerArray,
  index
) {
  // ...
  if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
    return
  }
  // ...
}

createComponent 的作用就是创建组件,这里对它的返回值做了个判断,如果返回 true 的话就直接结束。但是这时返回的不是 true

createComponent

// src/ore/dom/atch.js
/**
 * 如果 vnode 是一个组件,则执行 init 钩子,创建组件实例,并挂载
 * 然后为组件执行各个模块的 create 方法
 * @param {*} vnode 组件新的 vnode
 * @param {*} insertedVnodeQueue 数组
 * @param {*} parentElm oldVnode 的父节点
 * @param {*} refElm oldVnode 的下一个兄弟节点
 * @returns 如果 vnode 是一个组件并且组件创建成功,则返回 true,否则返回 undefined
 */
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
  let i = vnode.data
  if (isDef(i)) {
    // 组件实例时候已存在且keep-alive包裹
    const isReactivated = isDef(vnode.componentInstance) && i.keepAlive
    if (isDef(i = i.hook) && isDef(i = i.init)) {
      // 如果 vnode 是一个组件,条件满足,i 就是 init钩子函数。
      // 如果是被 keep-alive 包裹的组件,先执行 init 后会在执行 prepatch 钩子。
      i(vnode, false /* hydrating */)
    }
    // after calling the init hook, if the vnode is a child component
    // it should've created a child instance and mounted it. the child
    // component also has set the placeholder vnode's elm.
    // in that case we can just return the element and be done.
    if (isDef(vnode.componentInstance)) {
      // 如果 vnode 的实例存在
      // 执行各个模块的的 create 钩子,创建属性的、创建样式的、指令等
      initComponent(vnode, insertedVnodeQueue)
      // 将组件的 DOM 节点插入到父节点内
      insert(parentElm, vnode.elm, refElm)
      if (isTrue(isReactivated)) {
        // 组件被 keep-alive 包裹的情况,激活组件
        reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm)
      }
      return true
    }
  }
}

vnode 是一个组件 VNode,i 就是 init 钩子函数。

init

// src/ore/dom/reate-component.js
// patch 期间在组件 VNode 上调用的内联钩子
// inline hooks to be invoked on component VNodes during patch
const componentVNodeHooks = {
  // 初始化
  init (vnode: VNodeWithData, hydrating: boolean): ?boolean {
    if (
      vnode.componentInstance &&
      !vnode.componentInstance._isDestroyed &&
      vnode.data.keepAlive
    ) {
      // 被 keep-alive 包裹的组件
      // kept-alive components, treat as a patch
      const mountedNode: any = vnode // work around flow
      // 更新 VNode
      componentVNodeHooks.prepatch(mountedNode, mountedNode)
    } else {
      // 创建组件实例,即 new vnode.componentOptions.Ctor(options) => 得到 Vue 组件实例
      const child = vnode.componentInstance = createComponentInstanceForVnode(
        vnode,
        activeInstance
      )
      // 调用 $mount 方法,进入挂载阶段。
      child.$mount(hydrating ? vnode.elm : undefined, hydrating)
    }
  },
  // 更新 VNode
  prepatch (oldVnode: MountedComponentVNode, vnode: MountedComponentVNode) {
    // 新的 VNode 配置项
    const options = vnode.componentOptions
    // 旧的 VNode 组件实例
    const child = vnode.componentInstance = oldVnode.componentInstance
    // 用新的更新旧的
    updateChildComponent(
      child,
      options.propsData, // updated props
      options.listeners, // updated listeners
      vnode, // new parent vnode
      options.children // new children
    )
  }
  // ...
}

init 中,如果是被 keep-alive 包裹,则会调用 componentVNodeHooks.prepatch 方法用新的 vnode 配置去更新旧的 vnode 配置。
如果没有被 keep-alive 包裹,则通过 createComponentInstanceForVnode 创建 Vue 组件的实例。然后调用 $mount 挂载组件.

createComponentInstanceForVnode

// src/core/vdom/create-component.js
// new vnode.componentOptions.Ctor(options) => 得到 Vue 组件实例 
export function createComponentInstanceForVnode (
  // we know it's MountedComponentVNode but flow doesn't
  vnode: any,
  // activeInstance in lifecycle state
  parent: any
): Component {
  const options: InternalComponentOptions = {
    // 表示它是一个组件
    _isComponent: true,
    _parentVnode: vnode,
    // 表示当前激活的组件实例
    parent
  }
  // 检查内联模版渲染函数
  const inlineTemplate = vnode.data.inlineTemplate
  if (isDef(inlineTemplate)) {
    options.render = inlineTemplate.render
    options.staticRenderFns = inlineTemplate.staticRenderFns
  }
  // new VueComponent(options) => Vue 实例
  return new vnode.componentOptions.Ctor(options)
}

这里的 vnode.componentOptions.Ctor 对应的就是组件的构造函数。它实际继承于 Vue 的一个构造器 Sub

vnode.componentOptions.Ctor

// src/core/vdom/create-component.js
// context.$options._base = Vue
const baseCtor = context.$options._base
// 当 Ctor 为配置对象时,通过 Vue.extend 将其转为构造函数
// plain options object: turn it into a constructor
if (isObject(Ctor)) {
  Ctor = baseCtor.extend(Ctor)
}
//src/coreglobal-api/extend.js
Vue.extend = function (extendOptions: Object): Function {
    extendOptions = extendOptions || {}
    const Super = this
    const SuperId = Super.cid
    /**
     * 利用缓存,如果存在则直接返回缓存中的构造函数
     */
    const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {})
    if (cachedCtors[SuperId]) {
      return cachedCtors[SuperId]
    }
    const name = extendOptions.name || Super.options.name
    if (process.env.NODE_ENV !== 'production' && name) {
      validateComponentName(name)
    }
    // 定义 Sub 构造函数,和 Vue 构造函数一样
    const Sub = function VueComponent (options) {
      // 初始化
      this._init(options)
    }
    // 通过原型继承的方式继承 Vue
    Sub.prototype = Object.create(Super.prototype)
    Sub.prototype.constructor = Sub
    Sub.cid = cid++
    // 选项合并,合并 Vue 的配置项到 自己的配置项上来
    Sub.options = mergeOptions(
      Super.options,
      extendOptions
    )
    // 记录自己的基类
    Sub['super'] = Super
    // 初始化 props,将 props 配置代理到 Sub.prototype._props 对象上
    // 在组件内通过 this._props 方式可以访问
    if (Sub.options.props) {
      initProps(Sub)
    }
    // 初始化 computed,将 computed 配置代理到 Sub.prototype 对象上
    // 在组件内可以通过 this.computedKey 的方式访问
    if (Sub.options.computed) {
      initComputed(Sub)
    }
    // 定义 extend/mixin/use 这三个静态方法,允许在 Sub 基础上再进一步构造子类
    Sub.extend = Super.extend
    Sub.mixin = Super.mixin
    Sub.use = Super.use
    // 定义 component、filter、directive 三个静态方法
    ASSET_TYPES.forEach(function (type) {
      Sub[type] = Super[type]
    })
    // 递归组件的原理,如果组件设置了 name 属性,则将自己注册到自己的 components 选项中
    if (name) {
      Sub.options.components[name] = Sub
    }
    // 在扩展时保留对基类选项的引用。
    // 稍后在实例化时,我们可以检查 Super 的选项是否具有更新
    Sub.superOptions = Super.options
    Sub.extendOptions = extendOptions
    Sub.sealedOptions = extend({}, Sub.options)
    // 缓存
    cachedCtors[SuperId] = Sub
    return Sub
  }
}

new vnode.componentOptions.Ctor(options) 实例化其实就相当于 new Sub(options)。在 new Sub(options) 的过程中,调用 _init:

_init

// src/core/instance/init.js
Vue.prototype._init = function (options?: Object) {
  const vm: Component = this
  // ...
  if (options && options._isComponent) {
    // optimize internal component instantiation
    // since dynamic options merging is pretty slow, and none of the
    // internal component options needs special treatment.
    initInternalComponent(vm, options)
  } else {
    vm.$options = mergeOptions(
      resolveConstructorOptions(vm.constructor),
      options || {},
      vm
    )
  }
  //...
  if (vm.$options.el) {
    vm.$mount(vm.$options.el)
  }
}

这里因为 options._isComponenttrue,调用 initInternalComponent 合并了一些配置,最后由于组件的初始化没有 vm.$options.el ,所以这里的挂载会跳过。

回到 init 的过程中,在完成实例化的 _init 之后,接下来回执行 child.$mount(hydrating ? vnode.elm : undefined, hydrating)hydrating 表示服务端渲染,所以这里相当于执行 child.$mount(undefined, false) , $mount 中调用 mountComponent,然后 mountComponent 中又会调用 updateComponent :

updateComponent = () => {
  vm._update(vm._render(), hydrating)
}

接下来又会调用 vm._render() 生成组件的 VNode ,然后执行 vm._update 去渲染 VNode ,那么回到 _update,最后就是调用 __patch__,也就是 patch :

patch

// src/core/vdom/patch.js
return function patch (oldVnode, vnode, hydrating, removeOnly) {
  // ...
 // 新节点存在,旧节点不存在
  if (isUndef(oldVnode)) {
    isInitialPatch = true
    createElm(vnode, insertedVnodeQueue)
  }
  // ...
}

到这里又开始的 createElm 方法中:

createElm

// src/core/vdom/patch.js
function createElm (
  vnode,
  insertedVnodeQueue,
  parentElm,
  refElm,
  nested,
  ownerArray,
  index
) {
  // ...
  if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
    return
  }
  // 获取 Data 对象
  const data = vnode.data
  // 获取子VNode
  const children = vnode.children
  // 判断 tag
  const tag = vnode.tag
  if (isDef(tag)) {
    //...
    // 创建元素节点
    vnode.elm = vnode.ns
      ? nodeOps.createElementNS(vnode.ns, tag)
      : nodeOps.createElement(tag, vnode)
    setScope(vnode)
    /* istanbul ignore if */
    if (__WEEX__) {
      // ...
    } else {
      // 递归创建所有子节点(普通元素、组件)
      createChildren(vnode, children, insertedVnodeQueue)
      if (isDef(data)) {
        invokeCreateHooks(vnode, insertedVnodeQueue)
      }
      // 将节点插入父节点
      insert(parentElm, vnode.elm, refElm)
    }
    // ...
  } else if (isTrue(vnode.isComment)) {
    // 注释节点,创建注释节点并插入父节点
    vnode.elm = nodeOps.createComment(vnode.text)
    insert(parentElm, vnode.elm, refElm)
  } else {
    // 文本节点,创建文本节点并插入父节点
    vnode.elm = nodeOps.createTextNode(vnode.text)
    insert(parentElm, vnode.elm, refElm)
  }
}

这时候传入的 vnode 是组件的渲染 vnode ,也就是 render 之后的 vnode ,如果组件的根节点是普通元素,就创建元素节点,然后遍历子节点递归调用 createElm,过程中如果遇到的 VNode 是一个组件,则重复这个过程。这样就通过递归创建了完整的组件树。

在完成组件的整个 patch 过程后,最后执行 insert(parentElm, vnode.elm, refElm) 完成组件的 DOM 插入。

更新

还记得在响应式原理吗?但数据发生变化时,会触发 watcher 的回调函数。使组件进行更新。

updateComponent = () => {
  vm._update(vm._render(), hydrating)
}

new Watcher(vm, updateComponent, noop, {
  before () {
    if (vm._isMounted) {
      callHook(vm, 'beforeUpdate')
    }
  }
}, true /* isRenderWatcher */)

实际上还是调用了_update , patch 函数。patch 中通过 sameVnode 方法判断新节点和旧节点是否是同一节点,而进入不同的处理方式。

新旧节点不同

// src/core/vdom/patch.js
return function patch (oldVnode, vnode, hydrating, removeOnly) {
  // ...
  if (isUndef(oldVnode)) {
    // ...
  } else {
    // ...
    if (!isRealElement && sameVnode(oldVnode, vnode)) {
      // ...
    } else {
      if (isRealElement) {
        // replacing existing element
        // 旧节点的真实DOM
        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)
        )
        
        // 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)
        }
      }
    }
  }
}

新节点和旧节点不相同的更新只需要,用新的把旧的替换掉,过程大致就是:

  1. 已旧节点为参考点,使用 createElm 创建新节点,并插入 DOM 中。
  2. 更新父的占位符节点。
  3. 移除旧节点,当组件没有被 keep-alive 包裹,移除过程中,就会执行 beforeDestroydestroyed 钩子函数

新旧节点相同

重头戏来了,当新旧节点相同时,会调用 patchVnode 方法,我们常说的diff算法也就发生在这个过程中。

patchVnode

// src/core/vdom/patch.js
function patchVnode (
  oldVnode,
  vnode,
  insertedVnodeQueue,
  ownerArray,
  index,
  removeOnly
) {
  // 新旧节点相同,直接返回
  if (oldVnode === vnode) {
    return
  }
  if (isDef(vnode.elm) && isDef(ownerArray)) {
    // clone reused vnode
    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))
  ) {
    // 新旧节点都是静态的而且两个节点的 key 一样,并且新节点被 clone 了 或者 新节点有 v-once指令,则复用这部分节点
    vnode.componentInstance = oldVnode.componentInstance
    return
  }
  // 执行组件的 prepatch 钩子
  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
  // 全量更新新节点的属性,Vue 3.0 在这里做了很多的优化。
  if (isDef(data) && isPatchable(vnode)) {
    // 执行组件的 update 钩子
    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)
  }
  // patch 过程。
  if (isUndef(vnode.text)) {
    // 新节点不是文本节点。
    if (isDef(oldCh) && isDef(ch)) {
      // 新旧节点都有子节点,递归执行 diff 操作。
      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)
  }
}

在对比新旧 VNode 的时候主要包括三种类型操作:属性更新、文本更新、子节点更新。在 patchVnode 的流程中主要把其分为四个步骤:

  1. 执行 prepatch 钩子函数。
  2. 执行 update 钩子函数。
  3. 完成 patch 过程。
  4. 执行 postpatch 钩子函数。

这里重点关注 patch 过程,先是对 vnode 判断,如果 vnode 是文本节点且文本相同,则更新文本。如果不是文本节点,则做了这么几种情况的处理:

  • 新节点旧节点都有子节点且不相同,通过 updateChildren 来更新子节点。
  • 新节点有子节点,旧节点没有子节点,如果有文本先清空文本,然后通过 addVnodes 新增子节点。
  • 新节点没有子节点,旧节点有子节点,通过 removeVnodes 移除所有子节点。
  • 新节点是文本节点,且新旧文本不同,则更新文本。

在这些更新情况中,updateChildren 最为复杂,我们常说的 diff 双端比较也就发生在这里,重点关注一下。

updateChildren

// src/core/vdom/patch.js
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是一个特殊的标志,仅由 <transition-group> 使用,以确保被移除的元素在离开转换期间保持在正确的相对位置
  const canMove = !removeOnly
  if (process.env.NODE_ENV !== 'production') {
    // 检查新节点的 key 是否重复
    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)) {
      // 旧开始节点和新开始节点是同一个节点,执行 patch
      patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
      // patch 结束后旧开始和新开始的索引分别加 1
      oldStartVnode = oldCh[++oldStartIdx]
      newStartVnode = newCh[++newStartIdx]
    } else if (sameVnode(oldEndVnode, newEndVnode)) {
      // 旧结束和新结束是同一个节点,执行 patch
      patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
      // patch 结束后旧结束和新结束的索引分别减 1
      oldEndVnode = oldCh[--oldEndIdx]
      newEndVnode = newCh[--newEndIdx]
    } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
      // 旧开始和新结束是同一个节点,执行 patch
      patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
      // 处理被 transtion-group 包裹的组件时使用
      canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
      // patch 结束后旧开始索引加 1,新结束索引减 1
      oldStartVnode = oldCh[++oldStartIdx]
      newEndVnode = newCh[--newEndIdx]
    } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
      // 旧结束和新开始是同一个节点,执行 patch
      patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
      canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
      // patch 结束后,旧结束的索引减 1,新开始的索引加 1
      oldEndVnode = oldCh[--oldEndIdx]
      newStartVnode = newCh[++newStartIdx]
    } else {
      // 如果上面的四种假设都不成立,则通过遍历找到新开始节点在旧节点中的位置索引
      // 找到旧节点中每个节点 key 和 索引之间的关系映射 => oldKeyToIdx = { key1: idx1, ... }
      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)) {
          // 如果这两个节点是同一个,则执行 patch
          patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
          // patch 结束后将该旧节点置为 undefined
          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]
    }
  }
  // 走到这里,说明旧节点或者新节点被遍历完了
  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)
  }
}

updateChildren 主要作用是用一种高效的方式对比新旧 VNode 的 children 来获取差异,更新视图。 sameVnode 方法是对比两个节点是否相同。

图片1

循环之前,在新旧两组子节点的开始和结束位置都会创建变量索引,在循环过程中,这几个变量索引都会向中间靠拢。当 oldStartIdx > oldEndIdx 或者 newStartIdx > newEndIdx 时结束循环。

首先进行 oldStartVnodeoldEndVnodenewStartVnodenewEndVnode 两两交叉比较,做了四种假设。

假设旧开始和新开始或者旧结束和新结束相同,直接将该 VNode 节点进行 patchVnode 即可,就避免了一次循环,以提高执行效率,如下图:

图片2

如果旧开始和新结束相同,调用 patchVnode ,将真实DOM节点移动到 oldEndVnode 的后面。

图片3

如果旧结束和新开始相同,调用 patchVnode ,将真实DOM节点移动到 oldStartVnode 的前面。

图片4

如果上面四种假设均不成立,通过 key在旧节点中找对应的新开始,若存在执行 patchVnode ,同时移动到 oldStartVnode 的前面。

图片5

若是找不到一致的 key , 或者 key 相同但不是同一节点,这时候说明是新节点,调用 createElm 执行创建。

当循环结束时 oldStartIdx > oldEndIdx ,这时候旧节点已遍历完,新节点还没有,说明新节点比旧节点多,这时候需要将剩下的节点对应的 DOM 插入到真实的 DOM 中,调用 addVnodes 方法。

图片6

当循环结束时 newStartIdx > newEndIdx ,这时候新节点已遍历完,旧节点还没有,说明旧节点比新节点多,这时候需要将多余的节点删除。

图片7

相关链接

Vue源码解读(预):手写一个简易版Vue

Vue源码解读(一):准备工作

Vue源码解读(二):初始化和挂载

Vue源码解读(三):响应式原理

Vue源码解读(四):更新策略

Vue源码解读(五):render和VNode

Vue源码解读(六):update和patch

Vue源码解读(七):模板编译

如果觉得还凑合的话,给个赞吧!!!也可以来我的 个人博客 逛逛

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Vue源码解读(六):update和patch 的相关文章

随机推荐

  • STM32刷Micropython固件参考指南

    STM32刷Micropython固件指南 其实刷固件和普通的程序下载烧录无多大的差异 主要是其他因数的影响导致刷固件或刷完固件无法运行的情况和相关问题 刷固件教程 固件下载 目前所支持的stm32型号有这些 stm32f0 stm32f4
  • linux进阶05——Makefile(二)

    1 源代码 main c int main printf hello world n fun1 fun2 fun1 c void fun1 printf this is fun1 n fun2 c void fun2 printf this
  • BERT:Pre-training of Deep Bidirectional Transformers for Language Understanding

    BERT 个人翻译 并不权威 paper https arxiv org pdf 1810 04805 pdf BERT Pre training of Deep Bidirectional Transformers for Languag
  • sql语句大全+实例讲解

    1 创建3张表 学生表创建 CREATE table student Sno CHAR 9 PRIMARY KEY Sname CHAR 20 UNIQUE Ssex char 2 Sage SMALLINT Sdept char 20 课
  • LCD 驱动

    LCD的型号是 CM162 4 有U1 U2 外形尺寸 L W H mm 80 36 12 点数 mm 5 8 内藏控制器 SPLC 780 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 GND VDD VO
  • vue3+element-plus+js 对列表查询/重置条件 组件简单封装

    在写后台管理的时候会有很多列表 列表上面一般会有查询条件 对列表进行搜索查询 所以就想封装成为组件 就不需要每个页面写一堆的代码 直接循环出来进行遍历即可 1 封装子组件searchForm组件
  • 利用Bat命令批量修改文件名

    因为科研需求 需要把文件名规范统一命名 整体思路 先获得原始文件名字 带后缀 再导到excel里搞好新名字 构建好Bat的ren函数 完成修改 具体措施 1 读取原本文件名称 在相应的文件目录下 新建一个文本文件 并且打开输入 dir b
  • 移动端物理像素和设备独立像素

    https blog csdn net aiolos1111 article details 51880223 https www cnblogs com samwu p 5341056 html http www softwhy com
  • ifconfig命令详解

    在CU论坛里看到一个关于google面试的帖子 当中提到的一个面试题就是ifconfig命令的用法 所以今天就趁些机会在网上找了一些关于ifconfig的文章 转到这边来 大家一起学习 以下转自 http www photox cn IT
  • linux之date命令

    date 命令用于 显示 或 设置系统的时间或日期 格式 date 参数 日期格式 注意 date后面有一个空格 否则无法识别命令 shell对空格是很严格的 1 Linux date命令参数 日期时间格式符号 H 小时 以00 23来表示
  • x = torch.cat((x1, x2), dim=1) dim是什么意思,决定什么变量

    在这个例子中 x torch cat x1 x2 dim 1 意思是将 x1 和 x2 按照第一维拼接起来 得到新的 tensor x 变量 dim 1 决定了拼接的维度
  • re学习(29)攻防世界-CatFly(复原反汇编)

    因为这是一个 dll文件 在Linux上运行一下 找到主要函数 以及由上面三部分对应的代码部分 int64 fastcall main int a1 char a2 char a3 size t v3 rbx int16 v5 4 rsp
  • Docker安装Elasticsearch 8.x 、Kibana 8.x等

    这里我使用的是8 2 0版本 同时内容会介绍ik分词和elastic head的安装 elasticsearch java的配置 1 下载ik分词器插件 下载地址 https github com medcl elasticsearch a
  • 年轻人 vs 存款

    近日 有调查称 大概五分之一的年轻人存款在一万元以内 10万元存款是一个 坎 存款超过10万就会超过53 7 的人 年轻人 存款 两个词碰撞在一起 引来了广泛的关注和讨论 你认为年轻人存款难吗 可以从以下几个角度发表你的看法 存款 角度一
  • Redis入门之一

    设置后台进程 进入redis conf中的136行改成 yes 设置后台进程 修改bind 改成qianfeng01 改密码 找到第500行左右 requorepass 改成123456 登录的代码 查看 ps ef grep redis
  • 数据挖掘基础之数据库

    最近出现的一种数据库结构是数据仓库 1 3 2 小节 这是一种多个异种数据源在单个站点以统一的模式组织的存储 以支持管理决策 数据仓库 技术包括数据清理 数据集成和联机分析处理 OLAP OLAP 是一种分析技术 具有汇总 合并和聚集功能
  • RSA算法Java版(不要求支持大数)但实现了(dog

    RSA算法 支持大数 题目描述 C 中数据的类型与长度参考 因此 C 最大能支持的十进制是19位的整数 如果要支持更大的整数 需要实现Big Number类 RSA目前比较安全的密钥长度是2048位二进制 即是617位的十进制 因此 C 自
  • grafana 使用 Node Exporter for Prometheus Dashboard 监控服务器基础信息

    使用 Node Exporter for Prometheus Dashboard 监控服务器CPU 内存 磁盘 IO 网络 流量 温度等指标 当需要监控服务器的CPU 内存 磁盘 IO 网络 流量 温度等指标 可以使用 grafana 的
  • Eclipse 直接开发HANA UI5 ABAP等(提供完整配套软件 和jar包及操作文档)_SAP刘梦_新浪博客...

    之前写了HANA Studio 安装 ABAP UI5 插件等等 现在写下直接用Eclipse 有人说了现象 打开HANA Studio 做HANA建模 然后呢 打开个eclipse 做UI5 其实没必要 本来HAHA studio就是ec
  • Vue源码解读(六):update和patch

    Vue 的 update 是实例上的一个私有方法 主要的作用就是把 VNode 渲染成真实的 DOM 它在首次渲染和数据更新的时候被调用 在数据更新的时候会发生新 VNode 和 旧 VNode 对比 获取差异更新视图 我们常说的 diff