Vue中watch原理分析

Vue中Watch的初始化流程

  1. initWatch
  2. 遍历watch中的每一个watch函数,执行createWatcher,createWatcher有两个作用:获取到watch监听的回调和调用vm.$watch
  3. 执行vm.$watch,这个函数主要也是两个功能,判断是否是立即执行的监听回调,如果需要立即执行,那就将回调(也就是watch的handler)立即执行一遍。第二个功能是给每一个watch分配一个Watcher。
  4. 主要来分析一下,新建这个Watcher的过程都做了些什么。
var Watcher = function (vm, key, cb, opt) {
    this.vm = vm;
    this.deep = opt.deep;
    this.cb = cb;
    // 这里省略处理 xx.xx.xx 这种较复杂的key
    this.getter = function(obj) {
        return obj[key]
    };
    // this.get 作用就是执行 this.getter函数
    this.value = this.get();
};
Watcher.prototype.get = function() {
    // 这个getter会去实例上根据相应的key,读取相应的值,并保存在`this.value`上
    var value = this.getter(this.vm);
    // 如果设置了深度监听,那么会进行深度遍历
    if (this.deep)  traverse(value);
    return value
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值