Home

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

Object.defineProperty() 和 Proxy 对象,都可以用来对数据的劫持操作。
何为数据劫持呢?就是在我们访问或者修改某个对象的某个属性的时候,通过一段代码进行拦截行为,然后进行额外的操作,然后返回结果。那么vue中双向数据绑定就是一个典型的应用。
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>