数据双向绑定的原理

通过数据劫持来实现的

  1. <input type="text" />

  2. 演示 : V ==> M

//1. 拿到文本框
const txt = document.getElementById('txt')
//2. 时刻监听txt ,拿到最新的值
txt.oninput = function() {
 console.log(this.value)
 obj.name = this.value
}

//3. 数据模型
var obj = {}
let temp

Object.defineProperty(obj, 'name', {
 // 给属性赋值的时候会掉
 set: function(newVal) {
   console.log('调用了set', newVal)
   temp = newVal

   txt.value = newVal
},
 get: function() {
   console.log('调用了get')
   return temp
}
})
  1. V => M

//1. 获取 input的值,最新值
//2. 通过监听oninput 拿到最新值
//3. 把最新值赋值给 obj.name
//4. 就会调用了set方法,就会修改了数据
  1. M => V

//1. obj.name = 'xxx'
//2. 调用 set方法
//3. 把值赋值给input元素