计算属性

10/27/2021 vue

new Vue实例化vm过程中,涉及到了对state的初始化,其中就包括对计算属性的初始化

export function initState (vm: Component) {
  vm._watchers = []
  const opts = vm.$options
	
  // ......

  if (opts.computed) initComputed(vm, opts.computed) // 初始化计算属性
  // ......
}
1
2
3
4
5
6
7
8
9

# initComputed

initComputedinitState定义在同一文件中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)
      }
    }
  }
}
1
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.$datavm.$options.propsvm.$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)
}
1
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
    }
  }
}
1
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
		}
	}
})
1
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
  }

  // ......

}
1
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
    }
  }
}
1
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对应watcherget方法后,Dep.target会指向渲染watcher,所以会接着执行watcher.depend方法

export default class Watcher {

  // ......

  depend () {
    let i = this.deps.length
    while (i--) {
      this.deps[i].depend()
    }
  }

  // ......

}
1
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)
    }
  }
	
  // ......

}
1
2
3
4
5
6
7
8
9
10
11
12
13

然后每个属性的dep.subs对渲染watcher进行订阅,同样渲染watcher也会对计算属性依赖的每个属性的dep进行依赖收集,不过在依赖收集时会有去重处理,所以不会重复依赖和订阅

最后更新时间: 12/4/2022, 1:44:46 PM