Vue 源码学习之计算属性

前面讲了依赖收集和侦听属性,在 Watcher类里面还有一些属性和方法是计算属性的时候使用,计算属性是依赖其他的值来进行计算,它的特性是依赖的值如果没有变化,则页面更新的时候不会重新计算,它的计算结果会被缓存下来,达到一定的性能优化;

initState里面会执行 initComputed,对 computed属性进行初始化:

// src/core/instance/state.js
const computedWatcherOptions = {
    
     lazy: true }
function initComputed (vm: Component, computed: Object) {
    
    
    const watchers = vm._computedWatchers = Object.create(null)
    const isSSR = isServerRendering()

    for (const key in computed) {
    
    
        const userDef = computed[key]
        // computed 有两种方式,一种是函数,一种是对象
        // 函数形式直接取 userDef, 对象形式取对象的 get 属性
        const getter = typeof userDef === 'function' ? userDef : userDef.get
        if (process.env.NODE_ENV !== 'production' && getter == null) {
    
    
            warn(
                `Getter is missing for computed property "${
      
      key}".`,
                vm
            )
        }
	
        // 如果不是服务端渲染,则创建 watcher 实例
        if (!isSSR) {
    
    
            watchers[key] = new Watcher(
                vm,
                getter || noop,
                noop,
                computedWatcherOptions
            )
        }
        // 判断是否存在命名冲突,是则发出警告,否则调用 defineComputed 定义计算属性
        if (!(key in vm)) {
    
    
            defineComputed(vm, key, userDef)
        } else if (process.env.NODE_ENV !== 'production') {
    
    
            if (key in vm.$data) {
    
    
                warn(`The computed property "${
      
      key}" is already defined in data.`, vm)
            } else if (vm.$options.props && key in vm.$options.props) {
    
    
                warn(`The computed property "${
      
      key}" is already defined as a prop.`, vm)
            } else if (vm.$options.methods && key in vm.$options.methods) {
    
    
                warn(`The computed property "${
      
      key}" is already defined as a method.`, vm)
            }
        }
    }
}

initComputed中可以得知几个操作:

  • 循环遍历 computed的属性,对计算属性两种书写方式进行处理,如果是函数形式,直接获取值,如果是对象属性,获取对象相应 get属性;
  • 创建计算属性 watcher,创建时将 lazy: true选项作为参数传进去,表示是一个计算属性的 watcher
  • 判断是否存在命名冲突,如果不冲突,则调用 defineComputed,否则报出警告;

初始化计算属性时会调用 defineComputed, 它主要对用户传入的属性进行处理,将用户传入的 getset赋值给对象 sharedPropertyDefinition,然后利用 Object.defineProperty对计算属性进行劫持,根据依赖项的变化来判断是否需要重新计算;

// src/core/instance/state.js

// 普通对象的定义,用于 Object.defineProperty 传入的参数
const sharedPropertyDefinition = {
    
    
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
}

export function defineComputed (
    target: any,
    key: string,
    userDef: Object | Function
) {
    
    
    // 如果不是服务端渲染,则缓存标识为真
    const shouldCache = !isServerRendering()
    
    // 劫取计算属性的 get 和 set,赋值给 sharedPropertyDefinition 的 get 和 set
    if (typeof userDef === 'function') {
    
    
        sharedPropertyDefinition.get = shouldCache
            ? createComputedGetter(key)
        : createGetterInvoker(userDef)
        sharedPropertyDefinition.set = noop
    } else {
    
    
        sharedPropertyDefinition.get = userDef.get
            ? shouldCache && userDef.cache !== false
            ? createComputedGetter(key)
        : createGetterInvoker(userDef.get)
        : noop
        sharedPropertyDefinition.set = userDef.set || noop
    }
    
    if (process.env.NODE_ENV !== 'production' &&
        sharedPropertyDefinition.set === noop) {
    
    
        sharedPropertyDefinition.set = function () {
    
    
            warn(
                `Computed property "${
      
      key}" was assigned to but it has no setter.`,
                this
            )
        }
    }
    
    // 用 Object.defineProperty 将计算属性进行劫持,用户传入的 get 和 set 作为第三个参数
    Object.defineProperty(target, key, sharedPropertyDefinition)
}

createComputedGetter是计算属性的核心:

// src/core/instance/state.js
function createComputedGetter (key) {
    
    
    return function computedGetter () {
    
    
        // 获取相应的 watcher 实例
        const watcher = this._computedWatchers && this._computedWatchers[key]
        if (watcher) {
    
    
            // 计算属性缓存的关键,dirty 为真表示需要重新计算
            if (watcher.dirty) {
    
    
                watcher.evaluate()
            }
            // 让计算属性依赖项收集一遍外层的渲染 watcher
            if (Dep.target) {
    
    
                watcher.depend()
            }
            return watcher.value
        }
    }
}

class Watcher {
    
    
    // ... 
    get () {
    
    
        pushTarget(this)
        let value
        const vm = this.vm
        try {
    
    
            // 计算属性会执行用户自定义的 get,访问依赖项
            value = this.getter.call(vm, vm) 
        } catch (e) {
    
    
            if (this.user) {
    
    
                handleError(e, vm, `getter for watcher "${
      
      this.expression}"`)
            } else {
    
    
                throw e
            }
        } finally {
    
    
            if (this.deep) {
    
    
                traverse(value)
            }
            popTarget()
            this.cleanupDeps()
        }
        return value
    }
    update () {
    
    
        // 依赖项发生变化时,将 dirty 置为 true,下次访问就重新计算
        if (this.lazy) {
    
    
            this.dirty = true
        } else if (this.sync) {
    
    
            this.run()
        } else {
    
    
            queueWatcher(this)
        }
    }
    evaluate () {
    
    
        this.value = this.get()
        this.dirty = false
    }
    depend () {
    
    
        let i = this.deps.length
        while (i--) {
    
    
            this.deps[i].depend()
        }
    }
    // ...
}

从源码中我们可以看出:

  • dirty为真时,计算属性的值会重新计算,在 Watcher类中执行 get方法时,会执行用户自定义的 get,访问依赖项,从而将自己添加到依赖项的 dep里面;执行 update时,如果是计算 watcher,则只需要将 dirty置为 true,这样在下次访问时会进行重新计算;
  • watcher.depend的作用是让计算属性的依赖项收集外层 watcher,因为计算属性 watcher执行 update时只是将 dirty标识置为真,下次访问时重新计算,虽然值已经计算了,但是没有触发视图的更新,在前面的学习中,我们知道 Dep是用 targetStack模拟栈结构来存放 watcher实例,watcher每次调用 get方法时会将自身 pushtargetStack,执行完之后又 pop弹出,也就是说,当计算属性 watcher执行完 get之后,外层的渲染 watcher就会被置为 Dep.target,用 watcher.depend收集一遍外层渲染 watcher,这样就能达到计算属性的依赖项改变了,同时也更新视图的效果;

猜你喜欢

转载自blog.csdn.net/Ljwen_/article/details/124733473