关于Vue3.js的响应式学习总结

Vue3的响应式机制对比Vue2有了显著提升,它使用Proxy替代了Object.defineProperty。文章介绍了Vue3中如何通过Proxy实现数据响应,并通过副作用函数确保数据变化时的关联更新。同时,利用WeakMap管理副作用函数,解决了数据与函数的对应问题,优化了性能。
摘要由CSDN通过智能技术生成

关于Vue3的响应式总结

1. Vue2和Vue3的响应式区别

a. 从根本上来看,Vue2响应式是使用Object.defineProperty来实现的,而Vue3是使用Proxy来实现的
b. Vue2的响应式无法对数据进行相应,无法对object的属性增加和删除进行响应
c. 从性能上来说,Vue3性能上优于Vue2

2. Vue3的相应实现原理

let data = { text: '123' }
const obj = new Proxy(data, {
	get(target, key) {
		return target[key]
	}
	set(target, key, newVal) {
		target[key] = newVal
		return true
	}
})


// 上面是数据响应式的原理简易实现
// 那如何让数据和函数产生关联呢?答:副作用函数
// 先定义一个副作用函数接受的变量
let activeFun;
// 对proxy进行一手改造,美容美发先
const obj = new Proxy(data, {
	get(target, key) {
		// 先判断没有副作用函数先,undefine就是没有啦,喜仔没有副作用函数就直接返回值
		if(!activeFun) return target[key]
		// 如果有那就执行
		activeFun();
		return target[key]
	}
	set(target, key, newVal) {
		if( activeFun ) activeFun();
		target[key] = newVal
		return true
	}
})

// 呐呐呐,这就很奇怪了,那我岂不是每次都要执行同一个activeFun的函数了?而且,这样副作用函数没有对应关系啊!差评!
// 骚等,那指定不是啊,本场主角weakMap闪亮登场
let activeFun;
// fun作为一个副作用函数桶,对应的数据修改则进行打捞
let fun = new weakMap()
// 对proxy进行一手改造,美容美发先
const obj = new Proxy(data, {
	get(target, key) {
		// 先判断没有副作用函数先,undefine就是没有啦,喜仔没有副作用函数就直接返回值
		if(!activeFun) return target[key]
		let depMap = fun.get(target)
		if (!depMap) {
			// 建立target和map的关联
			fun.set(target, new Map())
			depMap = fun.get(target)
		}
		let depSet = depMap.get(key)
		if (!depSet) {
			depMap.set(key, new Set())
			depSet = depMap.get(key)
		}
		depSet.set(activeFun)
		return target[key]
	}
	set(target, key, newVal) {
		target[key] = newVal
		const depMap = fun.get(target)
		if (!depMap) return
		const depSet = depMap.get(key)
		depSet && depSet.forEach(fun => fun())
		return true
	}
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

元晖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值