Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写v-model简易版 #388

Open
DiF1202 opened this issue Jan 15, 2023 · 1 comment
Open

手写v-model简易版 #388

DiF1202 opened this issue Jan 15, 2023 · 1 comment

Comments

@DiF1202
Copy link
Contributor

DiF1202 commented Jan 15, 2023

<!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>
@jlx2002
Copy link
Contributor

jlx2002 commented Jan 16, 2023

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>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants