1.自己尝试实现了下vue的双向绑定原理
<body> <input type="text" id="input1Data"/> <input type="text" id="input2Data"/> <div id="input1DataView"></div> <div id="input2DataView"></div> </body> <script> const dataObj = { input1Data: '', input2Data: '' } const list=document.getElementsByTagName("input") for(let key in dataObj) { Object.defineProperty(dataObj, key, { get: function(val) { console.log('get', val) }, set: function(val) { document.getElementById(key+'View').innerHTML=val console.log(key) } }) } for(let i=0;i<list.length && list[i];i++) { let name = list[i].id list[i].addEventListener('keyup', function(e) { dataObj[e.target.id] = e.target.value }) } </script>
运行后的结果(满足双向绑定需求)