vue-computed原理
为什么computed可以缓存
evaluate () {
this.value = this.get()
this.dirty = false
}//计算属性的getter 获取计算属性的值时会调用
createComputedGetter (key) {
return function computedGetter () {
//获取到相应的watcher
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
//watcher.dirty 参数决定了计算属性值是否需要重新计算,默认值为true,即第一次时会调用一次
if (watcher.dirty) {
/*每次执行之后watcher.dirty会设置为false,只要依赖的data值改变时才会触发
watcher.dirty为true,从而获取值时从新计算*/
watcher.evaluate()
}
//获取依赖
if (Dep.target) {
watcher.depend()
}
//返回计算属性的值
return watcher.value
}
}
}总结
最后更新于