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-详解diff算法 #46

Open
PleaseStartYourPerformance opened this issue Jun 8, 2021 · 0 comments
Open

Vue-详解diff算法 #46

PleaseStartYourPerformance opened this issue Jun 8, 2021 · 0 comments

Comments

@PleaseStartYourPerformance
Copy link
Owner

PleaseStartYourPerformance commented Jun 8, 2021

深度优先,同层比较

1.当数据发生变化时,vue是怎么更新节点的?

渲染真实DOM的开销是很大的,比如有时候我们修改了某个数据,如果直接渲染到真实dom上会引起整个dom树的重绘和重排有没有可能我们只更新我们修改的那一小块dom而不要更新整个dom呢?diff算法能够帮助我们。
我们先根据真实DOM生成一颗virtual DOM,当virtual DOM某个节点的数据改变后会生成一个新的Vnode,然后Vnode和oldVnode作对比,发现有不一样的地方就直接修改在真实的DOM上,然后使oldVnode的值为Vnode。

diff的过程就是调用名为patch的函数,比较新旧节点,一边比较一边给真实的DOM打补丁。

2.diff的比较方式?

diff算法比较新旧节点的时候,比较只会在同层级进行, 不会跨层级比较。
image

 在如上图所示先从最上面的节点比较,在比较根节点的时候做的第一件事是先判断新旧两个节点有没有子节点,都有孩子则比较他们的孩子,进入孩子层级,若发现又有孩子则一直往下找孩子,如上图直接进入到第三层级,当发现往下都没有孩子时,则进入同层比较,同时在左侧两个橙色框内的孩子比较完后,也会返回上一级再按这种方式进行比较。

3.diff流程图

当数据发生改变时,set方法会让调用Dep.notify通知所有订阅者Watcher,订阅者就会调用patch给真实的DOM打补丁,更新相应的视图。
image

链接:https://www.cnblogs.com/wind-lanyan/p/9061684.html

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