vue中view-model双向绑定基础原理

利用Object.defineProperty进行数据劫持

代码如下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue V-M</title>
</head>
<body>
  <div id="ap">
    <input id="input" type="text"><br/>
    <div id="text"></div><br/>
    <button id="button" type="button">打印</button>
  </div>
  <script>
    var input = document.querySelector('#input');
    var text = document.querySelector("#text");
    var button = document.querySelector("#button");
    var data = {value:''};

    Object.defineProperty(data, 'value', {
      get:function(){
        console.log('get value ',input.value);
        return input.value;
      },
      set:function(value){
        console.log('set value ',value);
        text.innerHTML = value;
        input.value = value;
      }
    });

    input.addEventListener("keyup", function (e) {
      data.value = e.target.value;
    }, false)

    button.addEventListener('click',function(e){
      console.log('data ',data);
    },false);
  </script>
</body>
</html>

 

posted @ 2022-10-18 14:21  程序員劝退师  阅读(41)  评论(0编辑  收藏  举报