当前位置:首页 > VUE

手写vue双向绑定实现

2026-02-25 07:35:42VUE

实现 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实现绑定herf

vue实现绑定herf

Vue 中实现绑定 href 的方法 在 Vue 中绑定 href 属性可以通过多种方式实现,以下是几种常见的方法: 使用 v-bind 或简写 : 通过 v-bind 或简写 : 动态绑定 hre…

Vue数据绑定实现

Vue数据绑定实现

Vue 数据绑定的核心机制 Vue 的数据绑定基于响应式系统,通过 Object.defineProperty 或 Proxy 实现。当数据变化时,视图自动更新。 双向绑定的实现方式 v-mode…

实现vue动态绑定

实现vue动态绑定

动态绑定的基本语法 在Vue中,使用v-bind指令或简写:实现动态绑定,将数据属性与HTML元素的属性关联起来。例如动态绑定class或style: <div v-bind:class="…

vue实现双向滚动

vue实现双向滚动

实现双向滚动的 Vue 方法 双向滚动通常指两个关联的滚动区域(如表格的头部和内容部分)同步滚动。以下是几种实现方式: 使用事件监听和 scroll 方法 通过监听一个滚动区域的 scroll 事…

vue双向绑定实现

vue双向绑定实现

Vue 双向绑定实现原理 Vue 的双向绑定主要通过 v-model 指令实现,其核心是结合数据劫持(Object.defineProperty 或 Proxy)和发布-订阅模式。 数据劫持 Vu…

vue实现绑定页面

vue实现绑定页面

Vue 实现数据绑定到页面的方法 Vue.js 通过数据绑定机制实现数据和页面的同步更新,主要依赖响应式系统和模板语法。以下是几种常见的绑定方式: 双向绑定 (v-model) 使用 v-model…