<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vue双向数据绑定原理</title>
</head>
<body>
<input type="text" v-model="title" />
<input type="text" v-model="title" />
</body>
<script>
function View(){
const proxy = new Proxy({},{
get(obj, property){},
set(obj, property, value) {
document.querySelectorAll(`[v-model=${property}]`).forEach(item => {
item.value = value
})
}
})
this.init = function() {
const els = document.querySelectorAll("[v-model]")
els.forEach(item => {
item.addEventListener('keyup', function() {
proxy[this.getAttribute("v-model")] = this.value
})
})
}
}
new View().init()
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" v-model="name">
<input type="text" v-model="age">
<script>
function Bidirectional(value) {
function definePro(obj, key, value) {
observe(value);
Object.defineProperty(obj, key, {
get: function () {
return value;
},
set: function (newval) {
console.log('检测变化', newval);
value = newval;
document.querySelectorAll(`[v-model="${key}"]`).forEach(el => {
el.value = newval;
});
}
})
}
function observe(obj) {
if (!obj || typeof obj != 'object') {
return
}
for (let i in obj) {
definePro(obj, i, obj[i]);
document.querySelectorAll(`[v-model="${i}"]`).forEach(el => {
el.value = obj[i];
el.addEventListener('change', function () {
console.log(666)
obj[i] = el.value;
})
});
}
}
observe(value)
}
let obj = {
name: 'shuaizi',
age: 18,
}
Bidirectional(obj)
</script>
</body>
</html>