标题很长,内容很简单,实际上只是尝试了Object.defineProperty这个方法而已。
// index.html <!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>MVVM-DEMO</title> </head> <body> <div class="container"> <input id="input" type="text"> </div> <script src="../js/app.js"></script> </body> </html>
// app.js // 绑定数据 let demo = {} // 绑定元素 const el = document.querySelector('#input') // 添加事件 el.addEventListener('change', (e) => { demo.value = e.target.value }) // 数据拦截 Object.defineProperty(demo,'value',{ set: (v) => { if (demo._value !== v) { demo._value = v el.value = v } }, get: () => { return demo._value } })