Vue2.0使用Object.defineProperty
原理:通过使用 Object.defineProperty 来劫持对象属性的 geter 和 seter 操作,当数据发生改变发出通知
<!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="yingaxiang" content="width=device-width, initial-scale=1.0"> 6 <title>vue2.x数据双向绑定</title> 7 </head> 8 <body> 9 <div> 10 <input type="text" id="input"> 11 <span id="text"></span> 12 </div> 13 </body> 14 </html> 15 <script> 16 var obj = {}; 17 Object.defineProperty(obj, 'prop', { 18 get: function () { 19 return val; 20 }, 21 set: function (newVal) { 22 val = newVal; 23 document.getElementById('text').innerHTML = val; 24 } 25 }); 26 document.addEventListener('keyup', function (e) { 27 obj.prop = e.target.value; 28 }); 29 </script>
原理:通过ES6的新特性proxy来劫持数据,当数据改变时发出通知
<!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="yingaxiang" content="width=device-width, initial-scale=1.0"> 6 <title>vue3.0数据双向绑定</title> 7 </head> 8 <body> 9 <div> 10 <input type="text" id="input"> 11 <span id="text"></span> 12 </div> 13 </body> 14 </html> 15 <script> 16 var obj = {}; 17 var obj1 = new Proxy(obj, { 18 // target就是第一个参数obj, receive就是返回的obj(返回的proxy对象) 19 get: function (target, key, receive) { 20 // 返回该属性值 21 return target[key]; 22 }, 23 set: function (target, key, newVal, receive) { 24 // 执行赋值操作 25 target[key] = newVal; 26 document.getElementById('text').innerHTML = target[key]; 27 } 28 }) 29 document.addEventListener('keyup', function (e) { 30 obj1[0] = e.target.value; 31 }); 32 </script>