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的作用和工作原理吗?说说你对它的理解。 #3

Open
wangqilingaaa opened this issue Jan 22, 2020 · 0 comments

Comments

@wangqilingaaa
Copy link
Owner

Key的作用 :
1.key是给每一个vnode的唯一id,可以依靠key更准确更快的拿到oldvnode中对应的vnode节点.
2.key 的特殊属性主要用在 Vue 的虚拟 DOM 算法,在新旧 nodes 对比时辨识 VNodes。如果不使用 key,Vue 会使用一种最大限度减少动态元素并且尽可能的尝试就地修改/复用相同类型元素的算法。而使用 key 时,它会基于 key 的变化重新排列元素顺序,并且会移除 key 不存在的元素。(vue文档, https://cn.vuejs.org/v2/api/#key)
2.出发声明周期钩子(vue文档)
3.触发过度(vue文档)
工作原理:
使用key给每一个节点做一个唯一标识,diff算法就可以正确的识别此节点,对节点进行操作
举个例子:
如果在a,d,c,d,e节点中插入f节点


默认的diff算法是这样的


即把c更新成f d=>c e=> d 最后在插入e,
使用key给每一个节点做一个唯一标识,diff算法就可以正确的识别此节点,找到正确的位置区插入新的节点

https://www.zhihu.com/question/61064119/answer/183717717
Advanced-Frontend/Daily-Interview-Question#1

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