Vue实现双向数据绑定的原理:Proxy代理实现
<!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" v-model="title" />
<input type="text" v-model="title" />
<div v-bind="title"></div>
</body>
<script>
function View() {
let proxy = new Proxy(
{},
{
get(obj, property) {},
set(obj, property, value) {
obj[property] = value;
document
.querySelectorAll(
`[v-model="${property}"],[v-bind="${property}"]`
)
.forEach((el) => {
el.innerHTML = value;
el.value = value;
});
},
}
);
this.run = function () {
const els = document.querySelectorAll("[v-model]");
els.forEach((item) => {
item.addEventListener("keyup", function () {
proxy[this.getAttribute("v-model")] = this.value;
});
});
};
}
let view = new View().run();
</script>
</html>
效果如下: