本文是一篇vue.js源码学习笔记,适合对vue的数据响应实现有一定了解的同学,文中有表述不准确的地方还望指出。那么开始了
提示:文中会看到( 知识点:xxx )这样的标记表示在源码的相应位置打上标记, 方便大家阅读
一,先看computed的实现源码
// initState会在new Vue()时执行
export function initState (vm: Component) {
/*
other
*/
// 如果我们定义了comouted属性则执行initComputed
if (opts.computed) initComputed(vm, opts.computed)
/*
other
*/
}
复制代码
在同一个文件中找到initComputed的定义
function initComputed (vm, computed) {
// 往组件实例上添加一个_computedWatchers属性,保存所有的computed watcher
const watchers = vm._computedWatchers = Object.create(null)
// 对所有的computed属性遍历处理
for (const key in computed) {
// 将我们定义的computed属性值用userDef保存
const userDef = computed[key]
// 我们在定义computed时可以是一个函数,也可以是一个对象{get:function(){}, set:function(){}}
const getter = typeof userDef === 'function' ? userDef : userDef.get
// 数据响应过程中的watcher(注意第二个参数是我们刚才拿到的getter,记住了)
watchers[key] = new Watcher(
vm,
getter || noop, // 注意这里,注意这里,注意这里,(****知识点getter)
noop,
computedWatcherOpt