实现一个简易Vue(四)Dep 与 Watcher
发布日期:2021-05-07 18:33:30 浏览次数:23 分类:精选文章

本文共 862 字,大约阅读时间需要 2 分钟。

4. Dep

  • 功能

    • 收集依赖,添加观察者(watcher)
    • 通知所有观察者
  • 代码

class Dep {     constructor() {       // 存储所有的观察者    this.subs = []  }  // 添加观察者  addSub(sub) {       if (sub && sub.update) {         this.subs.push(sub)    }  }  // 发送通知  notify() {       // 遍历 subs 里所有的观察者,调用每个观察者的update方法去去更新视图    this.subs.forEach(sub => {         sub.update()    })  }}

5. Watcher

  • 功能

    • 当数据变化触发依赖, dep 通知所有的 Watcher 实例更新视图
    • 自身实例化的时候往 dep 对象中添加自己
  • 代码

class Watcher {     constructor(vm, key, cb) {       this.vm = vm    // data中的属性名称    this.key = key    // 回调函数负责更新视图    this.cb = cb    // 把watcher对象记录到Dep类的静态属性target    Dep.target = this    // 触发get方法,在get方法中会调用addSub    this.oldValue = vm[key]    Dep.target = null  }  // 当数据发生变化的时候更新视图  update() {       let newValue = this.vm[this.key]    // 当新的值和旧的值相等,return 停止执行     if (this.oldValue === newValue) {         return    }    this.cb(newValue)  }}
上一篇:vue双向数据绑定原理
下一篇:实现一个简易Vue(三)Compiler

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年03月30日 06时33分01秒