vue2 响应式原理(超简洁版)

网络上的相关文章又干又长,大多数时候只想知道vue2响应式的运转框架,不关注太多细节的东西,所以自己总结了这篇。

  • 三个步骤
    1. 数据劫持
    2. 依赖收集
    3. 派发更新

  • 四个方法
    1. observer
    2. Compiler
    3. watcher
    4. Dep

具体执行:

  • 在Observer中,对vue的data中的所有数据遍历递归,进行数据劫持:getter,setter
  • 在Compiler中,找到html中用到了变量的地方eg:<p>{{ name }}</p> , 对这个变量进行new Watcher(p标签, name, vm)(就是一指定元素的副作用函数),该Watcher()就是属性name依赖之一,页面有很多用到name属性的地方,也就是说name会有很有watcher,标记依赖之后
  • Dep进行依赖收集,如何收集?data中的属性哪些在页面中使用了,哪些就收集起来,所以在Observer的getter能知道哪里使用了,getter它会通知Dep进行watcher的收集,并且Dep它有一个notify() 函数,该函数会在Observer的setter中调用,当某个data的某属性改变了,调用setter,触发notify(),notify()会拿着该属性,通知该属性的所有watcher(),watcher() 中的update()方法会告诉下游方法更新页面

init

function defineReactive(obj: Object, key: string, ...) {
    const dep = new Dep()

    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get: function reactiveGetter () {
        ....
        dep.depend()
        return value
        ....
      },
      set: function reactiveSetter (newVal) {
        ...
        val = newVal
        dep.notify()
        ...
      }
    })
  }
  
  class Dep {
      static target: ?Watcher;
      subs: Array<Watcher>;

      depend () {
        if (Dep.target) {
          Dep.target.addDep(this)
        }
      }

      notify () {
        const subs = this.subs.slice()
        for (let i = 0, l = subs.length; i < l; i++) {
          subs[i].update()
        }
      }

mount

mountComponent(vm: Component, el: ?Element, ...) {

    new Watcher(vm, updateComponent, ...)
}

class Watcher {
  getter: Function;

  // 代码经过简化
  constructor(vm: Component, expOrFn: string | Function, ...) {
    ...
    this.getter = expOrFn
    Dep.target = this                 
    this.value = this.getter.call(vm, vm)  // 调用组件的更新函数, 在这一步收集到了依赖
    ...
  }
}

更新

notify () {
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值