效果图
- 初始值:
- 变化后
源码
<!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>
<h1 v-bind="name">123</h1>
<input type="text" v-model="name" />
<input type="text" v-model="name" />
<script>
function getValue(key) {
const directives = ["bind", "model"];
directives.forEach((directive) => {
document
.querySelectorAll(`[v-${directive}="${key}"]`)
.forEach((item) => {
switch (directive) {
case "bind":
item.innerHTML = proxy[key];
break;
case "model":
item.value = proxy[key];
break;
default:
break;
}
});
});
}
const proxy = new Proxy(
{ name: "初始值" },
{
get(obj, key) {
return obj[key];
},
set(obj, key, value) {
obj[key] = value;
getValue(key);
},
}
);
getValue("name");
document.querySelectorAll(`[v-model="name"]`).forEach((item) => {
item.addEventListener("keyup", () => {
proxy.name = item.value;
});
});
</script>
</body>
</html>