computed和watcher的区别


1、渲染watcher   默认是true
2、用户watcher   默认是user true
3、计算属性watcher  默认lazy true   deps []
4.watch和computed的区别?
      4.1 在内部会对变量取值,computed默认不会的
      4.2 computed 依赖的值不变 就不会重新执行
      4.3 变量可以用于模板的渲染 watch 一般是监听数据  不会用于模板的渲染

 内部原理 都是通过watcher来实现的

/**
 * 1、渲染watcher   默认是true
 * 2、用户watcher   默认是user true
 * 3、计算属性watcher  默认lazy true   deps []
 * 
 * 
 * 4.watch和computed的区别?
 *  4.1 在内部会对变量取值,computed默认不会的
 *  4.2 computed 依赖的值不变 就不会重新执行
 *  4.3 变量可以用于模板的渲染 watch 一般是监听数据  不会用于模板的渲染
 * 
 * 内部原理 都是通过watcher来实现的
 */

function initComputed(vm, computed) {

    // _computedWatchers 存放着所有的计算属性对应的watcher
    const watchers = vm._computedWatchers = {};
    for (let key in computed) {
        const userDef = computed[key];    //获取用户定义的函数
        const getter = typeof userDef === 'function' ? userDef : userDef.get;

        // 获得getter函数 lazy:true 表示的就是computed 计算属性
        // 内部会根据lazy属性,不去调用getter
        // 计算属性 可以直接通过vm来进行取值 所以将属性定义到实例上。
        watchers[key] = new Watcher(vm, getter, () => { }, { lazy: true })

        defineComputed(vm, key, userDef);
    }

}

const sharedPropertyDefinition = {
    enumerable: true,
    configurable: true,
    get: () => { }
}

// 讲属性定义到vm上
function defineComputed(target, key, userDef) {
    // 这里需要添加缓存效果
    if (typeof userDef === 'function') {
        sharedPropertyDefinition.get = createComputedGetter(key); 
    } else {
        sharedPropertyDefinition.get = createComputedGetter(key); 
        sharedPropertyDefinition.set = userDef.set || (()=>{});
    }
    Object.defineProperty(target,key,sharedPropertyDefinition);
}

// 添加缓存 通过watcher来添加的。
function createComputedGetter(key){
    return function(){ 
        // 拿到了刚才的watcher
        let watcher=this._computedWatchers[key];
        if(watcher.dirty){ // 如果dirty 为true,就调用用户的方法
            watcher.evaluate();
        }
        return watcher.value;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vues

刚好遇见你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值