美文网首页
34、双向数据绑定

34、双向数据绑定

作者: 苏码码 | 来源:发表于2022-01-10 10:49 被阅读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>
    

    相关文章

      网友评论

          本文标题:34、双向数据绑定

          本文链接:https://www.haomeiwen.com/subject/eagziltx.html