周日(2020-07-12)下了一天雨,闲来无事,就把vue的响应式原理从2.0-3.0手敲了一遍,最后实现了一个mini版的vue,有时间和大家慢慢分享。从上篇博客中我们知道vue3.0在数据的响应式上无疑做了很大的优化,性能得到大大提升。虽然vue3.0还没有正式发布,但是各大公众号已经闹得不亦说乎。
我们都知道vue2的响应式原理的实现依赖的是Object.defineProperty这个API,用它来为要实现响应式的数据设置getter和setter方法。如果数据多时就要循环遍历。循环遍历就会降低性能,所以vue3.0就摒弃了这个方法,改为使用ES6中的proxy来实现。而这个方法没有shim,不兼容低版本浏览器。所以vue3.0彻底摒弃了它们。
1.核心代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vue3.0响应式原理</title>
</head>
<body>
<div id="app">hello</div>
<script>
const data = {
msg: 'hello',
count: 0
}
// 设置代理
let vm = new Proxy(data, {
get(target, key) {
console.log('get,key:', key, target[key])
return target[key]
},
set(target, key, newValue) {
console.log("set,key:", key, newValue)
if (target[key] === newValue) {
return
}
target[key] = newValue
document.getElementById('app').textContent = target[key]
}
})
// 测试用例
vm.msg = "Hello World"
</script>
</body>
</html>