zoukankan      html  css  js  c++  java
  • vue双向绑定的简单实现(原创)

    简单模拟一下vue的双向绑定实现,代码比较粗糙,菜鸟一枚,欢迎各位大佬斧正

    1、实验环境:

    利用a、b两个input,a代表页面中的数据,b代表data中的数据

    2、原理:

    利用Object.defineProperty()方法实现数据的更新;使用oninput(IE下的)和onporpertychange(非IE下的)方法对input框中值的改变进行监听

    3、代码

    注:以下原生js实现

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
    </head>
    <body>
      a: <input type="text" id="a" oninput="aa(event)" onporpertychange="aa(event)">
         </br>
      b: <input type="text" id="b" oninput="bb(event)" onporpertychange="bb(event)">
    </body>
    </html>
    <script>
      var a = document.getElementById('a')
      var b = document.getElementById('b')
      var data = {}
      Object.defineProperty(data, "cell", {
        set: function(newValue) {
          if (newValue) {
            a.value = newValue
            b.value = newValue
          }
        }
      })
    </script>
    <script>
      var ie = !!window.ActiveXObject;
      console.log('111')
      if("onporpertychange" in a){
        document.getElementById("a").attachEvent("onporpertychange",function(e){
          console.log("input");
        })
        document.getElementById("b").attachEvent("onporpertychange",function(e){
          console.log("input");
        })
      } else {
        document.getElementById("a").addEventListener("oninput",function(e){
          console.log("input");
        })
        document.getElementById("b").addEventListener("oninput",function(e){
          console.log("input");
        })
      }
      function aa(e){
        data.cell = a.value
      }
      function bb(e){
        data.cell = b.value
      }
    </script>
  • 相关阅读:
    Python 中的map函数,filter函数,reduce函数
    编程中,static的用法详解
    C++ list容器系列功能函数详解
    python中的configparser类
    310实验室OTL问题----将写好的C++文件转换成Python文件,并将数据可视化
    310实验室OTL问题
    常量指针、指针常量、指向常量的指针常量
    Iterator迭代器的相关问题
    struts2中action中的通配符
    struts2访问servlet API
  • 原文地址:https://www.cnblogs.com/hrlin/p/9673920.html
Copyright © 2011-2022 走看看