深圳企业网站建设公司排名,网站开发试题,杭州做网站公司,网站模板找超速云建站vue实例组件初始化过程中#xff0c;在执行initState(vm)方法初始化状态时#xff0c;判断options.computed有值时会进行initComputed$1(vm,options.computed)处理
function initState(vm) {let options vm.$options;// 省略props methods data的处理// 处理计算属性comput…vue实例组件初始化过程中在执行initState(vm)方法初始化状态时判断options.computed有值时会进行initComputed$1(vm,options.computed)处理
function initState(vm) {let options vm.$options;// 省略props methods data的处理// 处理计算属性computedif (options.computed) {initComputed$1(vm, options.computed)}
}执行initComputed$1方法每个计算属性都会创建一个watcher观察者实例用来依赖追踪。然后执行defineComputed方法把每个计算属性都直接绑定在vm实例上
function initComputed$1(vm, computed) {let watchers Object.create(null)vm._computedWatchers watchersfor (let key in computed) {let userDef computed[key]let getter typeof userDef function ? userDef : userDef.get// 每个计算属性创建一个watcher观察者实例// lazy:true 默认不执行watchers[key] new Watcher(vm, getter, null, { lazy: true })defineComputed(vm, key, userDef);}
}执行defineComputed方法使用Object.defineProperty()进行数据劫持
let sharedPropertyDefinition {enumerable: true,configurable: true,get: function() {},set: function() {}
};function defineComputed(target,key,userDef) {if (typeof userDef function) {sharedPropertyDefinition.get createComputedGetter(key)sharedPropertyDefinition.set function() {}} else {sharedPropertyDefinition.get createComputedGetter(key)sharedPropertyDefinition.set userDef.set}Object.defineProperty(target,key,sharedPropertyDefinition)
}createComputedGetter方法的返回函数是计算属性的get方法当在模板编译挂载DOM时第一次读取了计算属性就是触发计算属性的get方法。首先是拿到该计算属性的watcher观察者实例执行watcher.evluate()将dirty值置为false触发计算属性对应watcher的getter方法。在此方法中访问响应式数据时会被响应式数据进行依赖收集最后将计算属性计算结果进行缓存与返回。
function createComputedGetter(key) {return function() {let watcher this._computedWatchers this._computedWatchers[key]if (!watcher) returnif (watcher.dirty) {watcher.evaluate();}// 计算属性中的响应式数据依赖收集渲染watcher// 保证响应式数据变化时触发渲染watcher的更新再触发计算属性的读取get方法if (Dep.target) { watcher.depend();}return watcher.value}
}// 针对computed的简写
class Watcher {constructor(vm, expOrFn, cb, options) {// ....this.vm vmthis.lazy truethis.dirty this.lazythis.getter expOrFn// 首次不会执行this.value this.lazy ? undefined : this.get();}evaluate() {this.value this.get();this.dirty false;}get() {pushTarget(this); // 赋值Deplet vm this.vm;let value this.getter.call(vm, vm);popTarget();this.cleanupDeps();return value}update() {if (this.lazy) {this.dirty true;}}
}当计算属性依赖追踪的响应式数据值有变化时会执行该计算属性对应watcher的update方法在该方法中会将dirty值置为true
class Watcher {......update() {if (this.lazy) {this.dirty true;}}
}下次再访问计算属性时会判断该计算属性对应的watcher实例中的dirty值。如果值为false表明计算属性依赖追踪的响应式数据未发生变化则无需进行任何处理直接拿上一次处理的缓存结果即可。如果值为true表示追踪的响应式数据有变化需重新执行watcher.evluate()更新缓存结果并将新结果返回。