34、双向数据绑定

2022-01-10  本文已影响0人  苏码码
<body>
 
  <input type="text" id="textInput"/>
  输入:<span id="textSpan"></span>
  <script>
var obj = {}
    //1.  Object.defineProperty()
   Object.defineProperty(obj,'name', {
      get: function() {
        return name
      },
      set: function(v) {
        console.log(v)
        textSpan.innerHTML = v
        name = v
      }
    })

    textInput.onkeyup = function(e) {
      obj.name = textInput.value
    }

//2. Proxy()
    var p = new Proxy(obj,{
      get: (target, key) => {
        return key in target ? target[key] : undefined
      },
      set:(target, key,value) => {
        target[key] = value
        textSpan.innerHTML = value
      }
    })

    window.addEventListener("keyup",(e) => {
      p.name = e.target.value
    })

      let arr = []
    var p = new Proxy(arr,{
      get: (target, key) => {
        console.log('get')
        return key in target ? target[key] : undefined
      },
      set:(target, key,value) => {
        console.log('set',key)
        target[key] = value
        textSpan.innerHTML = value
        console.log('set',target)
        return true
      }
    })

    window.addEventListener("keyup",(e) => {
      // p[0]=e.target.value
      p.push(e.target.value)
      // console.log(p)
    })

</script>
</body>
上一篇下一篇

猜你喜欢

热点阅读