<body>
<input type="text" v-model='content'>
<h4 v-bind="content"></h4>
<hr/>
<input type="text" v-model='title'>
<input type="text" v-model='title'>
<h4 v-bind="title">这里会更新</h4>
</body>
实现页面影响数据
// 首先实例化一个代理Proxy
let proxy = new Proxy({}, {
get(obj, property) {
},
set(obj, property, value) {
document.querySelectorAll(`[v-model="${property}"]`).forEach(i=>{
i.value=value
})
document.querySelectorAll(`[v-bind="${property}"]`).forEach(i=>{
i.innerHTML=value
})
}
})
//获取绑定元素
const els = document.querySelectorAll("[v-model]")
//遍历+keyup键盘抬起绑定
els.forEach(i => {
i.addEventListener("keyup", function () {
// 标签的v-model属性值 = this.value值
proxy[this.getAttribute("v-model")] = this.value
})
})
完整封装代码
function View(){
let proxy = new Proxy({},{
get(obj,property){
},
set(obj,property,value){
document.querySelectorAll(`[v-model="${property}"]`).forEach(i=>{
i.value = value
})
document.querySelectorAll(`[v-bind="${property}"]`).forEach(i=>{
i.innerHTML = value
})
}
})
this.init = function(){
const els = document.querySelectorAll("[v-model]")
els.forEach(i=>{
i.addEventListener("keyup",function(){
proxy[this.getAttribute("v-model")] = this.value
})
})
}
}
new View().init()