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中不要用index作为key?实际在问diff算法 #28

Open
JCHappytime opened this issue Mar 4, 2021 · 0 comments
Open
Labels
Vue Vue框架相关问题

Comments

@JCHappytime
Copy link
Owner

JCHappytime commented Mar 4, 2021

参考文章

1. 为什么Vue中不要用index作为key?
2.

前言

可以试想一下:在Vue开发中,我们的key是拿来做什么的?为什么不推荐用index作为key呢?接下来就将为你揭秘key的作用。

示例

有这样一段HTML代码:

<ul>
  <li>1</li>
  <li>2</li>
</ul>

我们知道在Vue中,都是先将节点转换为虚拟DOM,等到真正渲染的时候通过diff算法进行比对之后,才会成功渲染成我们需要的页面,而这个虚拟DOM是什么呢?其实就是JavaScript的一个对象。

那么上面示例的vdom节点大概就是下面这种形式:

{
  tag: 'ul',
  children: [
    { tag: 'li', children: [ { vnode: { text: '1' } } ] },
    { tag: 'li', children: [ { vnode: { text: '2' } } ] },
],
}
@JCHappytime JCHappytime added the Vue Vue框架相关问题 label Mar 4, 2021
@JCHappytime JCHappytime changed the title 为什么 Vue 中不要用 index 作为 key?实际在问diff算法 为什么Vue中不要用index作为key?实际在问diff算法 Mar 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Vue Vue框架相关问题
Projects
None yet
Development

No branches or pull requests

1 participant