Vue2中Watcher 与 Dep 与 State 的关系
名词解释
Watcher分为3种
1. 渲染Watcher - (在template中用到的 data or computed)
2. 计算Watcher - (组件的computed或者vuex的getter)
3. $watch的Watcher - (options.watch的内容或者vm.$watch)
State的来源有
- 组件的data及其子对象
- vuex的store.state
Dep(依赖)一般不太可见,是每一个data及其子对象都会生成一个Dep
比如有个state.channelInfo
对象, 那就可以通过store.state.channelInfo.__ob__.dep
获取到这个channelInfo的Dep
Dep有个属性是subs - 代表有哪些订阅者(Watcher),如果Dep关联的state发生改变,Dep会遍历subs通知到所有的订阅者(Watcher)。
长相图例
计算Watcher - vuex getter一般长这样

计算Watcher - 组件computed一般长这样

渲染Watcher一般长这样 expression里有render字样

$watch的Watcher一般长这样,触发的函数就是cb

解释一下下图的含义

也就是对于channelDetailInfo这个state对象,有9个订阅者(Watcher),都紧紧盯着他,一旦channelDetailInfo对象有改变,比如channelDetailInfo = {channel_name: ‘新房间’}, 9个订阅者就会触发相应的处理(更新视图or触发watch handler)
触发的反应
当渲染Watcher触发的时候,他会调用render()重新渲染视图
当计算Watcher触发的时候,如果他是lazy=true的,他会设置自己为dirty=true,然后在真正用的他的时候重新计算他的表达式。如果不是lazy的,就立刻触发表达式
当$watch的Watcher触发的时候,就触发对应的Handler
学习资料
https://medium.com/dailyjs/tracing-or-debugging-vue-js-reactivity-the-computed-tree-9da0ba1df5f9