我们打开文件 src/core/instance/state.js
,找到定义initComputed
函数的代码:
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)
}
}
}
}
可以看到第一步先创建了 watchers
变量并且赋值了一个空对象,同时给 vm
对象挂载了 _computedWatchers
属性。
const watchers = vm._computedWatchers = Object.create(null)
接下来判断了如果不是ssr
环境,就给key
添加一个Watcher
监听。
如果key
不存在vm
对象上面,就对key
进行Object.defineProperty
监听,否则就是计算属性的key
不能和data
以及prop
相同。
网友评论