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;
}
}