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

第60题(2019-10-17):Vue 中的 computed 是如何实现的 #62

Open
qappleh opened this issue Oct 17, 2019 · 1 comment
Open

第60题(2019-10-17):Vue 中的 computed 是如何实现的 #62

qappleh opened this issue Oct 17, 2019 · 1 comment

Comments

@qappleh
Copy link
Owner

qappleh commented Oct 17, 2019

No description provided.

@qappleh
Copy link
Owner Author

qappleh commented Oct 18, 2019


1.初始化 data 和 computed,分别代理其 set 和 get 方法,对 data 中的所有属性生成唯一的 dep 实例

2.对 computed 中的 属性生成唯一的 watcher,并保存在 vm._computedWatchers 中

3.访问计算属性时,设置 Dep.target 指向 计算属性的 watcher,调用该属性具体方法

4.方法中访问 data 的属性,即会调用 data 属性的 get 方法,将 data 属性的 dep 加入到 计算属性的 watcher , 同时该 dep 中的 subs 添加这个 watcher

5.设置 data 的这个属性时,调用该属性代理的 set 方法,触发 dep 的 notify 方法

6.因为时 computed 属性,只是将 watcher 中的 dirty 设置为 true

7.最后,访问计算属性的 get 方法时,得知该属性的 watcher.dirty 为 true,则调用 watcher.evaluate() 方法获取新的值

综合以上:也可以解释了为什么有些时候当computed没有被访问(或者没有被模板依赖),当修改了this.data值后,通过vue-tools发现其computed中的值没有变化的原因,因为没有触发到其get方法。
参考链接:Vue中computed实现原理及与method的区别

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

No branches or pull requests

1 participant