Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue中的 key 作用?为什么建议不用index作为key? #73

Open
GGXXMM opened this issue Dec 29, 2020 · 0 comments
Open

Vue中的 key 作用?为什么建议不用index作为key? #73

GGXXMM opened this issue Dec 29, 2020 · 0 comments
Labels

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Dec 29, 2020

作用

key的作用是为了更高效地更新虚拟DOM。

原理

源码中可知,key是 vnode 的唯一标识,用来判断两个节点是否相同。没有设置 key,则可能认为两个节点不相同,只能去做更新操作,这样造成大量的dom更新重复工作。

src\core\vdom\patch.js - sameVnode()

/**
 * 
 * @param {*} a oldVnode旧节点
 * @param {*} b vnode新节点
 */
// 节点key必须相同
// tag、注释、data是否存在、input类型是否相同
// 如果isAsyncPlaceholder是true,则需要asyncFactory属性相同
function sameVnode (a, b) {
  return (
    a.key === b.key && (
      (
        a.tag === b.tag &&
        a.isComment === b.isComment &&
        isDef(a.data) === isDef(b.data) &&
        sameInputType(a, b)
      ) || (
        isTrue(a.isAsyncPlaceholder) &&
        a.asyncFactory === b.asyncFactory &&
        isUndef(b.asyncFactory.error)
      )
    )
  )
}

为什么建议不用index作为key?

  1. 节点reserve场景:diff优化失效,判断 sameVnode key失效
  2. 删除节点场景:错误删除节点,列表节点混乱

参考:https://juejin.cn/post/6844904113587634184#heading-9

@GGXXMM GGXXMM added the vue label Dec 6, 2021
@GGXXMM GGXXMM changed the title Vue中的key作用和工作原理 Vue中的key作用和原理 Apr 2, 2023
@GGXXMM GGXXMM changed the title Vue中的key作用和原理 Vue中的 key 作用?为什么建议不用index作为key? May 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant