姓名:<span id="spanName"></span>
<br>
<input type="text" id="inpName">
<script>
//2.0 V-model实现原理
let obj = {
name: ''
};
let newObj = JSON.parse(JSON.stringify(obj));
Object.defineProperty(obj, 'name', {
get() {
return newObj.name
},
set(val) {
if (val == newObj.name) return
newObj.name = val
observer()
}
});
function observer() {
spanName.innerHTML = obj.name
inpName.value = obj.name
}
observer();
inpName.oninput = function() {
obj.name = this.value
} ===
// === === === === === === === === === === === === === === ==
//3.0 v - model实现原理
let obj = {}
obj = new Proxy(obj, {
get(target, prop) {
return target[prop]
},
set(target, prop, value) {
target[prop] = value
observer()
}
})
function observer() {
spanName.innerHTML = obj.name
inpName.value = obj.name
}
observer();
inpName.oninput = function() {
obj.name = this.value
}