Proxy proxy - simple implementation of two-way data binding (form processing)

Proxy can be understood as setting up a layer of "interception" before the target object. When the outside world accesses the object, it must go through this layer of interception, and Proxy acts as this mechanism, similar to the meaning of proxy. Filter and rewrite the object before the outside world accesses it.

  • Let's go directly to the code:
    html:
<fieldset>
    <legend>proxy双向数据绑定</legend>
    <label for="uname">姓名:<input type="text" id="uname" v-model="uName"></label><br>
    <label for="upass">密码:<input type="password" id="upass" v-model="uPass"></label>
    <hr>
    <!-- 实时变化 -->
    姓名:<h4 v-bind="uName"></h4><br>
    密码:<h4 v-bind="uPass"></h4>
</fieldset>

js:

<script>
    'use strict'
    function View() {
      const user = {}
      let proxy = new Proxy(user, {
        get(obj, property){},
        set(obj, property, value){}
      })
      this.init = function (){
        let inputs = document.querySelectorAll('[v-model]')
        // console.log(inputs);
        void [...inputs].map(item => {
          item.addEventListener('keyup', function(){
            console.log(this.value);
          })
        })
      }
    }
    new View().init()
</script>

insert image description here

The updated state achieved here, and then rendered to the page

js - update rendering in real time

<script>
    'use strict'
    function View() {
      const user = {}
      let proxy = new Proxy(user, {
        get(obj, property){
          return obj[property]
        },
        set(obj, property, value){
          // 数据存储
          obj[property] = value
          // 渲染
          document.querySelector(`[v-bind="${property}"]`).innerHTML = value
          return Reflect.set(obj, property, value);
          // Reflect.set()方法允许你在对象上设置属性。它的作用是给属性赋值并且就像 property accessor 语法一样,但是它是以函数的方式。
          // 设置成功true, 反之 false
          // return true
        }
      })
      this.init = function (){
        let inputs = document.querySelectorAll('[v-model]')
        // console.log(inputs);
        void [...inputs].map(item => {
          item.addEventListener('keyup', function(){
            // console.log(this.value);
            proxy[this.getAttribute('v-model')] = this.value
            console.log(user);
          })
        })
      }
    }
    new View().init()
</script>

insert image description here

Guess you like

Origin blog.csdn.net/qq_43531694/article/details/108849056