<!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>双向绑定</title>
</head>
<body>
<div id="app">
<input type="text" v-model="name"><br>
姓名: {{name}}<br>
<input type="text" v-model="age"><br>
年龄: {{age}}
</div>
</body>
<script>
let el = document.getElementById('app')
let template = el.innerHTML
let _data = {
name: 'blue',
age: 18,
}
let data = new Proxy(_data,{
set(obj,name,value){
obj[name] = value
console.log('数据改了')
render();
}
})
render();
function render(){
el.innerHTML = template.replace(/\{\{\w+\}\}/g,str=>{
str = str.substring(2,str.length-2)
return _data[str]
})
//找所以的v-model
Array.from(el.getElementsByTagName('input'))
.filter(ele=>ele.getAttribute('v-model'))
.forEach(input=>{
let name = input.getAttribute('v-model')
input.value = _data[name]
input.oninput= function(){
data[name] = this.value
}
})
}
</script>
</html>
网友评论