依存コレクションとリスナーのプロパティについては前に説明しました.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
。主に、ユーザーから渡されたプロパティを処理しget
、set
ユーザーから渡された と をオブジェクトに割り当て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
がtrue の場合、計算されたプロパティの値が再計算されます。Watcher
クラスでget
メソッドと、ユーザー定義get
のアクセス依存関係が実行され、それによって自身が依存関係に追加されます。実行時に、計算の場合はそれのみが実行されます。次回の訪問時に再計算されるように、に設定する必要があります。dep
update
watcher
dirty
true
watcher.depend
関数は、計算されたプロパティの依存関係が外側のレイヤーを収集できるようにすることですwatcher
.これは、計算されたプロパティwatcher
が実行されるフラグupdate
をtrueに設定するだけで、次にアクセスされたときに再計算されるためです.値は計算されていますが、実行されますビューの更新をトリガーしません. 以前の調査では、シミュレートされたスタック構造を使用してインスタンスがdirty
わかっています.メソッドが呼び出されるたびに、実行後にそれ自体がポップアップします.つまり、計算されたプロパティが実行されると、外側のレンダリングが に設定され、[外側のレイヤーのレンダリングを 1回収集、計算されたプロパティの依存関係が変更され、同時にビューを更新する効果が得られます。Dep
targetStack
watcher
watcher
get
push
targetStack
pop
watcher
get
watcher
Dep.target
watcher.depend
watcher