在new Vue
实例化vm
过程中,涉及到了对state
的初始化,其中就包括对计算属性的初始化
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
// ......
if (opts.computed) initComputed(vm, opts.computed) // 初始化计算属性
// ......
}
2
3
4
5
6
7
8
9
# initComputed
initComputed
和initState
定义在同一文件中src/core/instance/state.js
const computedWatcherOptions = { lazy: true }
function initComputed (vm: Component, computed: Object) {
// $flow-disable-line
const watchers = vm._computedWatchers = Object.create(null)
// computed properties are just getters during SSR
const isSSR = isServerRendering()
for (const key in computed) {
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
)
}
if (!isSSR) {
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
)
}
// 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)
}
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
initComputed
方法中,首先利用Object.create(null)
创建一个没有原型的对象watchers
,用于存储对应计算属性的watcher
实例,接着循环遍历computed
中定义的每个计算属性,并为每个计算属性实例化一个watcher
,然后根据计算属性名称存储到watchers
当中,接着将每个计算属性的名称在vm.$data
,vm.$options.props
,vm.$options.methods
中做比对,看是否有重复的键名,如果重复则会触发warn
提示,如果没有重名则会调用defineComputed
方法
# defineComputed
defineComputed
方法也定义在src/core/instance/state.js
中
export function defineComputed (
target: any,
key: string,
userDef: Object | Function
) {
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)
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
defineComputed
方法的逻辑非常简单,其实就是利用Object.defineProperty
方法将每个属性代理在vm
实例上,由于我们只是分析非服务端渲染部分,所以对象描述符中的getter
方法会由createComputedGetter
方法返回
# createComputedGetter
createComputedGetter
方法和definedComputed
方法定义在同一文件中
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
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
调用该方法,会返回computedGetter
方法,当在vm
实例上对该计算属性进行访问时,会先在vm._computedWatchers
中找到对应的watcher
,由于每个计算属性的watcher
选项中lazy
属性都为true
,所以实例化每个计算属性的watcher
过程中watcher.dirty
初始也为true
,接着会调用watcher.evaluate
方法
# 过程分析
在深入分析前,我们可以借助如下例子进行后续逻辑的分析
new Vue({
el: '#app',
template: `
<div id="app">
<div>{{ name }}</div>
<div>{{ age }}</div>
<div>{{ info }}</div>
</div>
`,
data: {
name: '张三',
age: 20
},
computed: {
info () {
return this.name + this.age
}
}
})
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
回到Watcher
定义部分
export default class Watcher {
// ......
/**
* Evaluate the getter, and re-collect dependencies.
*/
get () {
pushTarget(this)
let value
const vm = this.vm
try {
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
// ......
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
evaluate () {
this.value = this.get()
this.dirty = false
}
// ......
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
watcher.evaluate
方法会在内部调用this.get
方法,将当前计算属性对应的watcher
赋值给Dep.target
,接着执行当前计算属性对应的getter
方法(在我们分析的例子中就是return this.name + this.age
),然后又会进行依赖收集,Dep.target
返回为push
之前的状态和清除依赖的过程,最后会将当前计算属性的getter
方法返回的值赋给this.value
,然后将this.dirty
置为false
继续回到computedGetter
中
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
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
在执行watcher.get
方法中的watcher.getter
之前(就是执行计算属性的getter
方法,return this.name + this.age
),总是会把当前watcher
赋值给Dep.target
,执行之后会将Dep.target
的状态重置为赋值之前的状态,在我们上述例子中,在执行完计算属性info
对应watcher
的get
方法后,Dep.target
会指向渲染watcher
,所以会接着执行watcher.depend
方法
export default class Watcher {
// ......
depend () {
let i = this.deps.length
while (i--) {
this.deps[i].depend()
}
}
// ......
}
2
3
4
5
6
7
8
9
10
11
12
13
14
depend
方法会循环调用计算属性所依赖的每个属性的dep.depend
方法
export default class Dep {
// ......
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
// ......
}
2
3
4
5
6
7
8
9
10
11
12
13
然后每个属性的dep.subs
对渲染watcher
进行订阅,同样渲染watcher
也会对计算属性依赖的每个属性的dep
进行依赖收集,不过在依赖收集时会有去重处理,所以不会重复依赖和订阅