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

关于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
	}
})

你可能感兴趣的:(javascript,学习,开发语言)