initComputed
/**
* 初始化计算属性
* @param {*} vm
* @param {*} computed
*/
function initComputed (vm: Component, computed: Object) {
// $flow-disable-line
// 创建两个一样的空对象 watchers,vm._computedWatchers
const watchers = vm._computedWatchers = Object.create(null)
// computed properties are just getters during SSR
const isSSR = isServerRendering()
// 遍历计算属性 computed 对象
for (const key in computed) {
// 获取计算属性key对应的value:userDef
const userDef = computed[key]
// 如果对应的计算属性是函数,赋值给getter常量,或则将userDef.get赋值给getter
const getter = typeof userDef === 'function' ? userDef : userDef.get
// 非生产环境,如果getter不存在,报警告
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.
// 为每一个 getter 创建 watcher ---- computed watcher 和 watcher不同
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)) {// 如果计算属性不在vm实例上
// 定义计算属性,传入vm实例,计算属性的key,计算属性的value
defineComputed(vm, key, userDef)
} else if (process.env.NODE_ENV !== 'production') {
// 非生产环境,校验计算属性是否已经存在data或者props中,并给出相应的提示
if (key in vm.$data) {
warn(`The computed property "${key}" is already defined in data.`, vm)
} else if (vm.$options.props && key in vm.$s.props) {
warn(`The computed property "${key}" is already defined as a prop.`, vm)
}
}
}
}defineComputed
createComputedGetter
Last updated
Was this helpful?