简单模拟一下vue的双向绑定实现,代码比较粗糙,菜鸟一枚,欢迎各位大佬斧正
1、实验环境:
利用a、b两个input,a代表页面中的数据,b代表data中的数据
2、原理:
利用Object.defineProperty()方法实现数据的更新;使用oninput(IE下的)和onporpertychange(非IE下的)方法对input框中值的改变进行监听
3、代码
注:以下原生js实现
<!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>Document</title> </head> <body> a: <input type="text" id="a" oninput="aa(event)" onporpertychange="aa(event)"> </br> b: <input type="text" id="b" oninput="bb(event)" onporpertychange="bb(event)"> </body> </html> <script> var a = document.getElementById('a') var b = document.getElementById('b') var data = {} Object.defineProperty(data, "cell", { set: function(newValue) { if (newValue) { a.value = newValue b.value = newValue } } }) </script> <script> var ie = !!window.ActiveXObject; console.log('111') if("onporpertychange" in a){ document.getElementById("a").attachEvent("onporpertychange",function(e){ console.log("input"); }) document.getElementById("b").attachEvent("onporpertychange",function(e){ console.log("input"); }) } else { document.getElementById("a").addEventListener("oninput",function(e){ console.log("input"); }) document.getElementById("b").addEventListener("oninput",function(e){ console.log("input"); }) } function aa(e){ data.cell = a.value } function bb(e){ data.cell = b.value } </script>