计算属性的作用
这里我定义了一个简单的模板
可以看到method每次都会被重新调用,而computed只会执行一次,下面让我们从源码入手看看计算属性是如何实现缓存的
源码
初始化计算属性
计算属性的初始化是通过在src/core/instance/state.js下定义的initState方法中调用initComputed函数实现的
initState按照props,methods,data,computed,watch的顺序挨个执行初始化
// 初始化会被使用到的状态,状态包括props,methods,data,computed,watch五个选项
export function initState(vm: Component) {
// 首先,给实例上新增了一个属性_watchers,用来存储当前实例中所有的watcher实例,无论是使用vm.$watch注册的watcher实例还是使用watch选项注册的watcher实例,都会被保存到该属性中。
vm._watchers = []
const opts = vm.$options
// 先判断实例中是否有props选项,如果有,就调用initProps去初始化props选项;
if (opts.props) initProps(vm, opts.props)
// 再判断实例中是否有methods选项,如果有,就调用initMethods去初始化methods选项;
if (opts.methods) initMethods(vm, opts.methods)
// 接着再判断实例中是否有data选项,如果有,就调用initData去初始化data选项;如果没有,就把data当作空对象并将其转换成响应式;
if (opts.data) {
initData(vm)
} else {
// 如果没有,就把data当作空对象并将其转换成响应式;
observe((vm._data = {}), true /* asRootData */)
}
// 接着再判断实例中是否有computed选项,如果有,就调用computed选项初始化函数initComputed去初始化computed选项;
if (opts.computed) initComputed(vm, opts.computed)
// 最后判断实例中是否有watch选项,如果有,就调用watch选项初始化函数initWatch去初始化watch选项
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
// 以上就是initState函数的所有逻辑,其实你会发现,在函数内部初始化这5个选项的时候它的顺序是有意安排的,不是毫无章法的。如果你在开发中有注意到我们在data中可以使用props,在watch中可以观察data和props,之所以可以这样做,就是因为在初始化的时候遵循了这种顺序,先初始化props,接着初始化data,最后初始化watch。
}
initComputed
function initComputed(vm: Component, computed: Object) {
// 可以看到,在函数内部,首先定义了一个变量watchers并将其赋值为空对象,同时将其作为指针指向vm._computedWatchers 这是为了方便后续快速获取computedWatcher
const watchers = (vm._computedWatchers = Object.create(null))
// computed properties are just getters during SSR
const isSSR = isServerRendering()
for (const key in computed) {
// 接着,遍历computed选项中的每一项属性,首先获取到每一项的属性值,记作userDef,然后判断userDef是不是一个函数,如果是函数,则该函数默认为取值器getter,将其赋值给变量getter;如果不是函数,则说明是一个对象,则取对象中的get属性作为取值器赋给变量getter
const userDef = computed[key]
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实例,并将当前循环到的的属性名作为键,创建的watcher实例作为值存入watchers对象中。如下:
if (!isSSR) {
// 这里传入的computedWatcherOptions有一个非常重要的属性{lazy: true} 标记这是一个computedWatcher
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
)
}
}
Watcher
省略了一部分代码
export default class Watcher {
constructor(
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
// 如果是渲染函数的watcher vm._watcher = this 渲染watcher只有一个
if (isRenderWatcher) {
vm._watcher = this
}
//所有watcher都保存在_watchers中
vm._watchers.push(this)
// options
// 如果有options
if (options) {
this.deep = !!options.deep // 是否深度观察
this.user = !!options.user // 是否是用户自定义watcher
this.lazy = !!options.lazy // 是否懒惰观察 也就是computedWatcher
this.sync = !!options.sync // 是否同步求值
this.before = options.before // before回调钩子函数 组件更新前触发
} else {
// 否则都为false
this.deep = this.user = this.lazy = this.sync = false
}
this.cb = cb // 回调函数
this.id = ++uid // uid for batching
this.active = true
//这里是computedWatcher具有缓存的关键 this.dirty此时为true
this.dirty = this.lazy // for lazy watchers
this.expression =
process.env.NODE_ENV !== 'production' ? expOrFn.toString() : ''
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = noop
process.env.NODE_ENV !== 'production' &&
warn(
`Failed watching path: "${expOrFn}" ` +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
// lazy为true 说明是computedWatcher 不会调用this.get() 也就是不会求值
this.value = this.lazy ? undefined : this.get()
}
}
可以看到computedWatcher不同于其他watcher的地方是它的dirty ==lazy 都为true
function initComputed(vm: Component, computed: Object) {
//fineComputed`函数为实例`vm`上设置计算属性
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
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
)
}
}
}
}
defineComputed
export function defineComputed(
target: any,
key: string,
userDef: Object | Function
) {
// sharedPropertyDefinition 默认的属性描述符
//ouldCache,用于标识计算属性是否应该有缓存。
const shouldCache = !isServerRendering()
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(target, key, sharedPropertyDefinition)
}
可以看到计算属性有没有缓存主要在于是否将getter设置为createComputedGetter函数的返回结果
createComputedGetter
function createComputedGetter(key) {
return function computedGetter() {
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
if (watcher.dirty) {
watcher.evaluate()
}
if (Dep.target) {
watcher.depend()
}
return watcher.value
}
}
}
可以看到,该函数内部返回了一个computedGetter函数,所以其实是将computedGetter函数赋给了sharedPropertyDefinition.get。当获取计算属性的值时会执行属性的getter,而属性的getter就是sharedPropertyDefinition.get,也就是说最终执的computedGetter函数。
该函数首先从_computedWatchers中读取要获取的计算属性的watcher
const watcher = this._computedWatchers&& this._computedWatchers[key]
接着判断watcher 是否存在 如果存在 则判断其dirty值是否为true 还记得在初始化computedWatcher时dirty为true 所以会走watcher.evaluate
watcher.evaluate
evaluate() {
this.value = this.get()
this.dirty = false
}
evaluate中才是真正的读值,然后再次把dirty设为false
function createComputedGetter(key) {
return function computedGetter() {
// 获取当前要读取的计算属性的watcher
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
// 如果watcher.dirty为true 则调用watcher.evaluate
if (watcher.dirty) {
watcher.evaluate()
}
if (Dep.target) {
watcher.depend()
}
return watcher.value
}
}
}
当下一次读取计算属性的值时,由于dirty为false 所以会直接返回watcher.value
通过demo验证流程
定义一个按钮 点击触发change事件,由于计算属性缓存的特性,在没有修改count值为2之前
doubleComputed 只会打印一次,修改之后doubleComputed会被再次打印
断点调试一下
此时count就保存了doubleComputed的watcher
当count发送改变时会触发dep.notify()通知所有watcher调用update方法
xi
修改count 触发watcher.update
看一下显示效果
'dubleComputed'只被打印了2次