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

155.[vue]你知道vue中key的作用和工作原理吗?说说你对它的理解。 #155

Open
webVueBlog opened this issue Apr 2, 2020 · 2 comments
Labels
vue vue

Comments

@webVueBlog
Copy link
Member

[vue]

@webVueBlog webVueBlog added the vue vue label Apr 2, 2020
@webVueBlog
Copy link
Member Author

key的作用主要是为了高效的更新虚拟DOM,
其次,用于强制替换元素/组件而不是重复使用它,如触发生命周期和过渡。

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

@webVueBlog
Copy link
Member Author

vue在进行虚拟DOM对比中,判断是否为同一元素的首要判断条件为对比两个元素的key、然后再进行其它条件判断。为不同元素设置不同的key值,可以加快diff算法的精确度以及速度,如果多个元素设置同一key值,将会影响diff算法的精确度。
也可以通过改变同一元素的key值,达到每次更新都直接替换元素的效果

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