proxy代理-简单实现双向数据绑定(表单处理)

Proxy可以理解成,在目标对象之前架设一层 “拦截”,当外界对该对象访问的时候,都必须经过这层拦截,而Proxy就充当了这种机制,类似于代理的含义,它可以对外界访问对象之前进行过滤和改写该对象。

  • 我们直接上代码:
    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>

在这里插入图片描述

到此实现的更新状态,接下来渲染到页面

js-实时更新渲染

<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>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值