vue依赖缓存_[VUE]computed属性的数据响应和依赖缓存实现过程

本文深入探讨Vue.js中computed属性的实现原理,从initState到initComputed,再到Watcher和createComputedGetter函数,揭示了computed属性的数据响应和依赖缓存过程。当模板中使用computed属性时,会触发依赖收集、脏检查和计算值更新。当依赖项变更,只有相关computed属性的dirty标志才会变为true,从而触发重新计算。
摘要由CSDN通过智能技术生成

本文是一篇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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值