Vue2.0双向绑定原理(二)

这边接着上文继续讲解vue的dom的双向绑定的源码解析。上文讲到了dep和watcher的设计,以及他们之间是如何进行关联的。这篇开始讲解vdom在这个基础上的应用。

  1. 整个过程为,vue在编译template时生成虚拟dom。虚拟dom中的属性就是上篇文章讲到的data(大体可以这样理解),这里面包含dep。
  2. 虚拟dom也会生成一个watcher,这个watcher和dep关联到一起,这时候如果数据发生了变化,就会通知watcher,更新dom。

通过源码来理解这个过程:

一. vue的init部分,init后会调用$mount的方法

Vue.prototype._init = function (options?: Object) {

    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }

二. 继续看$mount方法具体实现,这里面会调用mountComponent,在mountComponent中会生成一个watcher。这里面有一个细节值得注意,给watcher参数中传入了一个updateComponent = function () {
vm._update(vm._render(), hydrating);
};
这个方法,vm._render表示生成虚拟dom,vm._update表示把虚拟dom更新到真实的dom中。从这里面是不是可以领悟到dom和数据直接的双向绑定呢?

Vue.prototype.$mount = function (
  el,
  hydrating
) {
  return mountComponent(
    this,
    el && query(el, this.$document),
    hydrating
  )
};
function mountComponent (
  vm,
  el,
  hydrating
) {


  // we set this to vm._watcher inside the watcher's constructor
  // since the watcher's initial patch may call $forceUpdate (e.g. inside child
  // component's mounted hook), which relies on vm._watcher being already defined
  new Watcher(vm, updateComponent, noop, {
    before: function before () {
      if (vm._isMounted && !vm._isDestroyed) {
        callHook(vm, 'beforeUpdate');
      }
    }
  }, true /* isRenderWatcher */);
  hydrating = false;

  // manually mounted instance, call mounted on self
  // mounted is called for render-created child components in its inserted hook
  if (vm.$vnode == null) {
    vm._isMounted = true;
    callHook(vm, 'mounted');
  }
  return vm
}

总结:
这里结合上篇文章解释说明下,new Watcher会执行自身的get方法,这时候Dep.target指向当前的watcher对象。同时这个get方法会调用updateComponent,在执行生成虚拟dom时,会执行对应数据的getter方法,这时候数据的dep就把当前的watcher加入的dep的订阅列表中了。运行时,数据发生变化就会notify这个watcher,从而实现双向绑定。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值