Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

手写v-model简易版

DiF1202 opened this issue · comments

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <button id="myBtn">改变username</button>
        <input type="text" id="myInput">
        <h1 id="myTitle"></h1>
    </div>
</body>
<script>
    let userinfo = {
        username: '小明',
    };
    //开始监控
    watcher();
    function watcher() {
        Object.defineProperty(userinfo, "username", {
            set(value) {
                updateDom(value);
            },
            get(val) {
                return val;
            },
        });
    }
    //更新dom数据
    function updateDom(value) {
        document.querySelector('#myInput').value = value;
        document.querySelector('#myTitle').innerHTML = value;
    }
    //给input绑定input事件,实时修改username的值
    document.querySelector('#myInput').oninput = function (e) {
        let value = e.target.value;
        userinfo.username = value;
    }
    //给button绑定点击事件,修改username的值
    document.querySelector('#myBtn').onclick = function () {
        let value = '小明';
        userinfo.username = value;
    }
</script>

</html>
commented

v-model 原理: 根据v-bind 的单向数据传值进行初始化后,通过input事件监听表单内容,表单内容变化后同时更新 响应式数据

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <input type="text" id="ipt" />
      <p>{{content}}</p>
    </div>
  </body>

  <script>
    new Vue({
      el: "#app",
      data: {
        content: "hello ",
      },
      mounted: function () {
        // 初始化时根据 v-bind 赋值
        const input = document.getElementById("ipt");
        input.value = this.content;
        // 绑定输入事件,实时监听并更新 响应式数据
        input.addEventListener("input", () => {
          this.content = input.value;
        });
      },
    });
  </script>
</html>