这一次 彻底理解Vue的watch实现原理及其实现方式(转)


画一张watch的简单工作流程图:

把上文的 Dep,Oberver,Wather拿过来并做部分更改(增加收集依赖去重处理):

Dep代码如下:

//标识当前的Dep id
let uidep = 0
class Dep{
    constructor () {
        this.id = uidep++
        // 存放所有的监听watcher
        this.subs = []
      }
 
      //添加一个观察者对象
      addSub (Watcher) {
        this.subs.push(Watcher)
      }
 
      //依赖收集
    depend () {
        //Dep.target 作用只有需要的才会收集依赖
        if (Dep.target) {
          Dep.target.addDep(this)
        }
    }
 
    // 调用依赖收集的Watcher更新
    notify () {
        const subs = this.subs.slice()
        for (let i = 0, l = subs.length; i < l; i++) {
          subs[i].update()
        }
      }
}
 
Dep.target = null
const targetStack = []
 
// 为Dep.target 赋值

function pushTarget (Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = Watcher
}
function popTarget () {
Dep.target = targetStack.pop()
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM