Home

Object.defineProperty 及 实现数据双向绑定

Vue2.x 是使用 Object.defindProperty(),来进行对对象的监听的。

Vue3.x 版本之后就改用Proxy进行实现的。

示例代码

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Object.defineProperty 及 实现数据双向绑定</title>
    <input type="text" />
    <h1></h1>
  </head>

  <body>
    <script>
      const ipt = document.querySelector("input");
      const h = document.querySelector("h1");
      let hanObj = {
        name: "",
        _name: "",
      };
      Object.defineProperty(hanObj, "name", {
        get() {
          return hanObj._name;
        },
        set(sval) {
          hanObj._name = sval;
          h.innerHTML = sval;
          ipt.value = sval;
        },
      });
      ipt.oninput = function () {
        hanObj.name = this.value;
      };
    </script>
  </body>
</html>