Proxy 代理对象
Vue3 Proxy 双向绑定原理
一定要触发set,才能够修改到界面的数据。
因为Object.defineproperty 如果对象是数组,不会触发set,所以在vue2.0中,数组并不是响应式的。
因为new Proxy 可以对数组进行代理,修改数组中数据的时候,也会触发set,一旦触发set,就可以在set中修改界面的数据,做到响应式效果
<!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>Document</title>
</head>
<body>
<input type="text" id="ipt">
<p id="op"></p>
<script>
let obj = { txtVal: '输入框的默认值' }
let newObj = new Proxy(obj, {
get(target, property) {
console.log("target", target);
console.log("property", property);
return target[property]
}
})
ipt.value = newObj.txtVal
op.innerHTML = newObj.txtVal
addEventListener('input', (e) => {
console.log(e.target.value);
op.innerHTML = e.target.value
})
</script>
</body>
</html>
手动输入内容 p标签的内容也会改变
封装 myReactive
<!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>Document</title>
</head>
<body>
<input type="text" id="ipt">
<p id="op"></p>
<script>
let obj = { txtVal: '输入框的默认值' }
function myReactive(obj) {
return new Proxy(obj, {
get(target, property) {
return target[property]
},
set(target, property, newValue) {
ipt.value = newValue; // 输入框的值
op.innerHTML = newValue // p标签展示的值
}
})
}
let newO = myReactive(obj);
addEventListener('input', (e) => {
newO.txtval = e.target.value
})
</script>
</body>
</html>
手写 vue3 reactive
<!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>Document</title>
</head>
<body>
<input type="text" id="ipt">
<p id="op"></p>
<script>
let obj = { txtVal: '输入框的默认值' }
function myReactive() {
return new Proxy(obj, {
get(target, property) {
return target[property]
}
})
}
myReactive(obj)
ipt.value = obj.txtVal
op.innerHTML = obj.txtVal
</script>
</body>
</html>