企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
### 初始化 computed & computed 原理 ![](https://img.kancloud.cn/a5/8d/a58d13d37cc838814c7795b27c0de8b9_2086x1594.png) 1. 初次渲染时,循环所有computed,并且为每一个computed 添加一个 watcher 监听,并把 dirty 的初始值设置为 lazy传入的值 1. 读取computed的值时,使用 watcher 计算一次值, 会把watcher的 dirty 设置成 false 2. 数据发生改变时,把 dirty 设置成 true 3. 再次读取 computed,通过dirty判断返回值是否发生变化,如果发生变化,会重新计算一下computed的值,并把dirty设置成false。如果结果和上次不一样,计算属性的watcher会通知组件的watcher,进行重新渲染 ![](https://img.kancloud.cn/17/bd/17bdc8bdd192d4c956263d0871323466_1667x407.png) ## initData ![](https://img.kancloud.cn/9d/61/9d615305fc950475ebb37f34de29971d_1578x796.png) ## initComputed ![](https://img.kancloud.cn/63/52/635267493a8e4e561118233209561063_1742x798.png) * 为每个 computed 的属性,生成一个 watcher 对象 * 对每一个属性调用了defineComputed方法(本质和data一样,代理了自己的set和get方法),将 computed 的值放入到 watcher 的 getter 中保存起来 * dirty 为 true 时调用 watcher 的 evaluate,将当前watcher 放入 Dep.target 中,并调用 getter 函数,计算当前的 computed 的值 * 当 computed 的值(函数)调用了响应式数据data,就会触发 data 的 get 方法。 * 判断 Dep.target 为 true时,进行依赖收集 **将该 data的 dep 放入当前 watcher 的 newDeps 中** ![](https://img.kancloud.cn/3d/06/3d068d985bf1a177f58cd6422d301d36_1772x1196.png) **当 data 更新时,computed 是如何更新的** ![](https://img.kancloud.cn/65/a1/65a10c15f6bebefe26de8b99573469e4_1776x790.png) ## 总体分析 ![](https://img.kancloud.cn/24/81/2481c45959678b9fc0cf805db08135d8_1252x600.png) https://www.jianshu.com/p/d95a7b8afa06 ### 问题: 1. computed 和 watch 有什么不同