现在的框架中实现双向绑定已经十分方便,这里在原生html中实现一下.
<!--
* @Description: proxy实现数据双向绑定
* @Author: owen
* @Date: 2021-07-15 00:30:02
* @LastEditTime: 2021-07-15 00:40:54
-->
<!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="content">
<input type="text" v-model="content">
<button v-bind="content">hello world</button>
<script>
function View(){
const proxy=new Proxy({},{
get(obj,property){
},
set(obj,property,value){
document.querySelectorAll(`[v-model=${property}]`).forEach((item)=>{
item.value = value
})
document.querySelectorAll(`[v-bind=${property}]`).forEach((item)=>{
item.innerHTML = value
})
},
})
this.init = function(){
document.querySelectorAll("[v-model]").forEach((item)=>{
item.addEventListener("keyup",function(){
proxy[this.getAttribute("v-model")] = item.value
})
})
}
}
new View().init()
</script>
</body>
</html>```
菜鸟学习记录,手写加深印象