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与虚拟dom的作用 #47

Open
Kelichao opened this issue Aug 17, 2020 · 0 comments
Open

vue中key与虚拟dom的作用 #47

Kelichao opened this issue Aug 17, 2020 · 0 comments

Comments

@Kelichao
Copy link
Owner

Kelichao commented Aug 17, 2020

https://cn.vuejs.org/v2/api/#key

还是文档溜

key 的特殊 attribute 主要用在 Vue 的虚拟 DOM 算法,在新旧 nodes 对比时辨识 VNodes。如果不使用 key,Vue 会使用一种最大限度减少动态元素并且尽可能的尝试就地修改/复用相同类型元素的算法。而使用 key 时,它会基于 key 的变化重新排列元素顺序,并且会移除 key 不存在的元素。

有相同父元素的子元素必须有独特的 key。重复的 key 会造成渲染错误。

最常见的用例是结合 v-for:

<ul>
  <li v-for="item in items" :key="item.id">...</li>
</ul>

它也可以用于强制替换元素/组件而不是重复使用它。当你遇到如下场景时它可能会很有用:

完整地触发组件的生命周期钩子
触发过渡
例如:

<transition>
  <span :key="text">{{ text }}</span>
</transition>

当 text 发生改变时, 总是会被替换而不是被修改,因此会触发过渡。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant