当前位置:首页 > VUE

手写vue双向绑定实现

2026-02-25 07:35:42VUE

手写vue双向绑定实现

手写vue双向绑定实现

实现 Vue 双向绑定的核心原理

Vue 的双向绑定基于 Object.definePropertyProxy(Vue 3)实现数据劫持,结合发布-订阅模式实现视图与数据的自动同步。以下是手写简化版实现:

数据劫持与响应式

class Observer {
  constructor(data) {
    this.walk(data);
  }

  walk(data) {
    if (!data || typeof data !== 'object') return;
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key]);
    });
  }

  defineReactive(obj, key, val) {
    const dep = new Dep();
    this.walk(val); // 递归处理嵌套对象
    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get() {
        Dep.target && dep.addSub(Dep.target); // 收集依赖
        return val;
      },
      set(newVal) {
        if (newVal === val) return;
        val = newVal;
        dep.notify(); // 通知更新
      }
    });
  }
}

依赖收集与发布订阅

class Dep {
  constructor() {
    this.subs = [];
  }

  addSub(sub) {
    this.subs.push(sub);
  }

  notify() {
    this.subs.forEach(sub => sub.update());
  }
}

class Watcher {
  constructor(vm, key, cb) {
    this.vm = vm;
    this.key = key;
    this.cb = cb;
    Dep.target = this;
    this.oldValue = vm[key]; // 触发getter
    Dep.target = null;
  }

  update() {
    const newValue = this.vm[this.key];
    if (newValue !== this.oldValue) {
      this.cb(newValue);
      this.oldValue = newValue;
    }
  }
}

编译器实现

class Compiler {
  constructor(el, vm) {
    this.vm = vm;
    this.el = document.querySelector(el);
    this.compile(this.el);
  }

  compile(node) {
    node.childNodes.forEach(child => {
      if (this.isElementNode(child)) {
        this.compileElement(child);
      } else if (this.isTextNode(child)) {
        this.compileText(child);
      }
      if (child.childNodes.length) {
        this.compile(child);
      }
    });
  }

  compileElement(node) {
    Array.from(node.attributes).forEach(attr => {
      if (this.isDirective(attr.name)) {
        const dir = attr.name.substring(2);
        this[dir] && this[dir](node, attr.value);
      }
    });
  }

  text(node, key) {
    this.update(node, key, 'text');
  }

  model(node, key) {
    this.update(node, key, 'model');
    node.addEventListener('input', e => {
      this.vm[key] = e.target.value;
    });
  }

  update(node, key, dir) {
    const updaterFn = this[`${dir}Updater`];
    updaterFn && updaterFn(node, this.vm[key]);
    new Watcher(this.vm, key, value => {
      updaterFn(node, value);
    });
  }

  textUpdater(node, value) {
    node.textContent = value;
  }

  modelUpdater(node, value) {
    node.value = value;
  }

  isDirective(attr) {
    return attr.startsWith('v-');
  }

  isElementNode(node) {
    return node.nodeType === 1;
  }

  isTextNode(node) {
    return node.nodeType === 3;
  }
}

整合实现

class Vue {
  constructor(options) {
    this.$options = options;
    this.$data = options.data();
    this.observe(this.$data);
    new Compiler(options.el, this);
  }

  observe(data) {
    new Observer(data);
  }
}

使用示例

<div id="app">
  <input v-model="message" />
  <div v-text="message"></div>
</div>

<script>
  new Vue({
    el: '#app',
    data() {
      return { message: 'Hello Vue' };
    }
  });
</script>

关键点说明

  • 数据劫持:通过 Object.defineProperty 拦截数据的读写操作
  • 依赖收集:在 getter 中收集依赖的 Watcher 实例
  • 派发更新:在 setter 中通知所有 Watcher 执行更新
  • 指令解析:编译模板时解析 v-modelv-text 等指令
  • 视图更新:通过 Watcher 实现数据变化时的自动视图更新

以上实现省略了数组处理、虚拟 DOM 等复杂逻辑,但完整展示了 Vue 双向绑定的核心机制。

标签: 绑定双向
分享给朋友:

相关文章

vue怎么实现双向

vue怎么实现双向

Vue 双向绑定的实现方式 Vue 中实现双向绑定的核心机制是 v-model 指令,它结合了属性绑定和事件监听,适用于表单元素或自定义组件。 表单元素的双向绑定 在原生表单元素(如 input、s…

实现vue数据绑定

实现vue数据绑定

Vue数据绑定的实现方式 Vue.js通过数据劫持和发布-订阅模式实现数据绑定,核心是响应式系统。以下是主要实现方法: 双向数据绑定(v-model) <input v-model="mess…

vue动态绑定实现原理

vue动态绑定实现原理

Vue动态绑定的核心原理 Vue的动态绑定主要通过数据劫持结合发布者-订阅者模式实现。当数据发生变化时,视图会自动更新,这一机制被称为响应式系统。 数据劫持与响应式 Vue使用Object.defi…

实现Vue双向数据绑定

实现Vue双向数据绑定

Vue 双向数据绑定的实现原理 Vue 的双向数据绑定是通过 v-model 指令实现的,其核心基于 数据劫持 和 发布-订阅模式。具体实现分为以下几个部分: 数据劫持(Object.defineP…

vue怎么实现数据绑定

vue怎么实现数据绑定

Vue 数据绑定的实现方式 Vue 的数据绑定主要通过指令和响应式系统实现,以下是核心方法: 双向数据绑定(v-model) v-model 指令用于表单元素与数据的双向绑定: <input…

vue数据绑定实现表格

vue数据绑定实现表格

Vue 数据绑定实现表格的方法 基础表格绑定 使用 v-for 指令循环渲染表格行,绑定动态数据到表格单元格: <template> <table> <th…