<div id="test"> name:{{name}} age:{{age}}</div><script> let el = document.getElementById('test'); let datainner = { name:"Jack", age:"18" } let template = el.innerHTML; let data = new Proxy(datainner,{ set(obj,name,value){ console.log(name+"的值被操纵成了value"+value) obj[name]=value; console.log("数据改变了"); render() } }) data.name="Jack Chen"</script>
可以监控到data数据的改变,然后就可以将数据渲染到html中,就可以实现es6数据同步到视图层
最终代码
<script> let el = document.getElementById('test'); let datainner = { name:"Jack", age:"18" } let template = el.innerHTML; let data = new Proxy(datainner,{ set(obj,name,value){ console.log(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); console.log(datainner[str]); return datainner[str] }) }</script>