<input id="ipt" value="" />
<p id="txt"></p>
<script>
let ipt = document.getElementById('ipt')
let txt = document.getElementById('txt')
let obj = {}
// 利用Object.defineProperty
Object.defineProperty(obj, 'age', {
get() {
return age
},
set(val) {
ipt.value = val
txt.innerHTML = val
}
})
ipt.oninput = function(e) {
obj.age = parseInt(e.target.value)
}
// 利用proxy代理
const newObj = new Proxy(obj, {
get(target, key, receiver) {
return Reflect.get(target, key, receiver)
},
set(target, key, value, receiver) {
ipt.value = value
txt.innerHTML = value
return Reflect.set(target, key, value, receiver)
}
})
ipt.oninput = function(e) {
newObj.age = parseInt(e.target.value)
}
</script>
简单实现双向数据绑定
最新推荐文章于 2023-06-09 11:42:46 发布