Vue 2.0 与 Vue 3.0 响应式原理比较
作者:互联网
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue 响应式原理</title>
</head>
<body>
<div id="msg">
里斯
</div>
<div id="count">
里斯
</div>
<script>
window.log = console.log
let data = {
msg: '张三',
count: 10,
}
let vm = {}
// Vue 2.0 响应式原理
// for (const key in data) {
// Object.defineProperty(vm, key, {
// enumerable: true,
// configurable: true,
// get() {
// log('get', data[key])
// return data[key]
// },
// set(newVal) {
// log('set', newVal)
// if (data[key] === newVal) return
// data[key] = newVal
// document.querySelector("#" + key).textContent = newVal
// }
// })
// }
//-----------------------
// Vue 3.0 响应式原理
vm = new Proxy(data, {
get(target, key) {
log('get', target[key], key)
return target[key]
},
set(target, key, newVal) {
log('set', newVal, key)
if (target[key] === newVal) return
target[key] = newVal
document.querySelector("#" + key).textContent = newVal
}
})
//-----------------------
vm.msg = '李四'
vm.count = 10
log(vm.msg, vm.count)
</script>
</body>
</html>
标签:Vue,3.0,vm,newVal,key,target,2.0,data,log 来源: https://www.cnblogs.com/llyk/p/15223485.html