zoukankan      html  css  js  c++  java
  • 数据双向绑定的原理

    通过数据劫持来实现的

    1. <input type="text" id="txt" />

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

     

     

    懦夫从未启程,弱者死在途中
  • 相关阅读:
    函数、对象
    webpack配置
    创智培训内容
    oracle方法
    Weblogic
    药店
    ip
    jdk账号
    ansible
    目录编码
  • 原文地址:https://www.cnblogs.com/oliviazhang/p/13528914.html
Copyright © 2011-2022 走看看