使用es6 Proxy代理 完成数据双向绑定
创建js文件
function createProxy(data,selector){
const proxy = new Proxy(data,{
get(target,key){
return target[key]
},
set(target,key,value){
map.get(key).value = value
const els2 = document.querySelectorAll(`[v-bind = "${key}"]`)
els2.forEach(item=>{
item.innerHTML = value
})
return target[key] = value
}
})
const map = new Map()
const $el = document.querySelector(selector)
$el.childNodes.forEach(el =>{
if ( el.nodeName !== "INPUT") return
const attributes = el.attributes
for(let a = 0;a<attributes.length;a++){
if(attributes[a].nodeName !== "v-model") continue
el.addEventListener('input',function(e){
proxy[attributes[a].nodeValue] = el.value
})
map.set(attributes[a].nodeValue,el)
}
})
map.forEach((value, key)=>{
const els2 = document.querySelectorAll(`[v-bind = "${key}"]`)
els2.forEach(item=>{
item.innerHTML = proxy[key]
})
value.value = proxy[key]
})
return proxy
}
创建html文件
<!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>
<form action="" id="userForm">
账号:<input type="text" v-model="name"> <br><br>
密码:<input type="text" v-model="password"> <br><br>
年龄:<input type="text" v-model="age"> <br><br>
</form>
<div v-bind = "name"></div>
<button id="btn1">表单提交</button>
<button id="btn2">改变年龄,加个1</button>
<script src="./v-model.js"></script>
<script>
const user = { name: '小明', password: '123', age: 10 }
const userProxy = createProxy(user, '#userForm')
console.log(userProxy);
document.querySelector('#btn1').onclick = function () {
console.log(user);
}
document.querySelector('#btn2').onclick = function () {
userProxy.age++
}
</script>
</body>
</html>