vue2 双向数据绑定实现

vue2 双向数据绑定实现

1. html 文件

<!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>vue2双向数据绑定实现</title>
</head>

<body>
  <div id="app">
    <input type="text" v-model="name.firstName" placeholder="姓氏"><span>姓氏:{{name.firstName}}</span><br>
    <input type="text" v-model="name.lastName" placeholder="名称"><span>名称:{{name.lastName}}</span><br>
    <input type="text" v-model="phone" placeholder="手机号"><span>手机号:{{phone}}</span>
  </div>
  <!-- 自定义 vue.js 文件 -->
  <script src="./vue.js"></script>
  <script>
    const vm = new Vue({
      el: '#app',
      data: {
        name: {
          firstName: '张',
          lastName: '三'
        },
        phone: '12312'
      }
    })
    console.log(vm);
  </script>
</body>

</html>

2. vue.js 文件

class Vue {
  constructor(obj_instance) {
    this.$data = obj_instance.data;
    this.$el = document.querySelector(obj_instance.el);
    Observer(this.$data);
    Compile(this);
  }
}

// 数据劫持 - 监听实例里的数据
function Observer(data_instance) {
  // 递归出口
  if (!data_instance || typeof data_instance !== 'object') return;
  const dependency = new Dependency();
  // 循环为每个属性进行劫持
  Object.keys(data_instance).forEach(key => {
    let value = data_instance[key];
    Observer(value); // 递归实现子属性数据劫持
    Object.defineProperty(data_instance, key, {
      // configrable 描述属性是否配置,以及可否删除
      configurable: true,
      // enumerable 描述属性是否会出现在for in 或者 Object.keys()的遍历中
      enumerable: true,
      get() {
        // 将订阅者加入依赖示例的数据
        Dependency.temp && dependency.addSub(Dependency.temp);
        return value;
      },
      set(newValue) {
        value = newValue;
        Observer(newValue);
        dependency.notify();
      }
    });
  });
}

// HTML 模板解析 - 替换 DOM 内容
function Compile(vm) {
  // 创建文档碎片
  const fragment = document.createDocumentFragment();
  let child;
  while ((child = vm.$el.firstChild)) {
    fragment.append(child);
  }
  // 替换文档碎片内容
  function fragment_compile(node) {
    const pattern = /{{\s*(\S+)\s*}}/;
    if (node.nodeType === 3) {
      const regex = pattern.exec(node.nodeValue);
      const xxx = node.nodeValue;
      if (regex) {
        const value = regex[1]
          .split('.')
          .reduce((pre, current) => pre[current], vm.$data);
        // 替换
        node.nodeValue = xxx.replace(pattern, value);
        // 创建订阅者
        new Watcher(vm, regex[1], newValue => {
          node.nodeValue = xxx.replace(pattern, newValue);
        });
      }
      return;
    }
    if (node.nodeType === 1 && node.nodeName.toLowerCase() === 'input') {
      let key = node.attributes['v-model'].nodeValue;
      const value = key
        .split('.')
        .reduce((pre, current) => pre[current], vm.$data);
      node.value = value;
      // 创建订阅者
      new Watcher(vm, key, newValue => {
        node.value = newValue;
      });
      // 为 input 节点添加 input 监听事件
      node.addEventListener('input', e => {
        const keyArr = key.split('.');
        const arr = keyArr.reduce((pre, current) => {
          if (!pre[current] || typeof pre[current] !== 'object') {
            return pre;
          }
          return pre[current];
        }, vm.$data);
        arr[keyArr[keyArr.length - 1]] = e.target.value;
      });
    }
    node.childNodes.forEach(child => fragment_compile(child));
  }
  // 开始替换
  fragment_compile(fragment);
  // 将整理好的文档碎片加入文档中
  vm.$el.appendChild(fragment);
}

// 依赖 - 收集和通知订阅者
class Dependency {
  constructor() {
    this.subscribers = [];
  }
  addSub(sub) {
    this.subscribers.push(sub);
  }
  notify() {
    this.subscribers.forEach(sub => sub.update());
  }
}

// 订阅者
class Watcher {
  constructor(vm, key, callback) {
    this.vm = vm;
    this.key = key;
    this.callback = callback;
    // 临时属性 - 触发getter
    Dependency.temp = this;
    key.split('.').reduce((pre, current) => pre[current], vm.$data);
    Dependency.temp = null;
  }
  update() {
    const value = this.key
      .split('.')
      .reduce((pre, current) => pre[current], this.vm.$data);
    this.callback(value);
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

soul g

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值