zoukankan      html  css  js  c++  java
  • 实现一个最小版本vue(五)之watcher

    watcher

    功能

    • 数据发生变化触发依赖,dep通知所有watcher更新视图

    • 自身实例化的时候往dep对象中添加自己

    • 结构

    实现思路

    data中每个属性,都会创建一个dep对象,dep收集依赖时,把所有依赖该属性的观察者添加到dep里的subs数组里,setter里触发依赖,调用dep的notify,通知所有关联的watcher,watcher负责更新视图

    代码

    class Watcher {
      constructor (vm, key, cb) {
        this.vm = vm
        // data中的属性名称
        this.key = key
        // callback更新视图
        this.cb = cb
        // 当前watcher对象记录到dep的target静态属性中
        Dep.target = this
        // vm[key]这里,先触发vue里的getter,vue里的getter触发observer的get方法,get方法里会调用addSub,把当前Watcher对象添加到dep
        this.oldValue = vm[key]
        // 重置,防止重复添加
        Dep.target = null
      }
    
      // 当数据变化时,更新视图
      update () {
        // 先获取最新的
        let newValue = this.vm[this.key]
        if (this.oldValue === newValue) {
          return
        }
        // 如果不等,调用cb进行更新
        this.cb(newValue)
      }
    }
    
  • 相关阅读:
    kill tomcat with netstat
    windows cmd命令显示UTF8设置
    rtx没有振动功能
    手动加载rvm
    RESTful Java client with Apache HttpClient
    Set Up Git on windows also use github
    lcs.py 最长公共子串算法
    如何:对代理使用 IP 切换
    这个博客站点不错
    a case study
  • 原文地址:https://www.cnblogs.com/Evo1uti0n/p/13267831.html
Copyright © 2011-2022 走看看