当前位置:首页 > VUE

手写vue双向绑定实现

2026-02-25 07:35:42VUE

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

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

手写vue双向绑定实现

数据劫持与响应式

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 指令实现,其核心是结合数据劫持(Object.defineProperty 或 Proxy)和发布-订阅模式。 数据劫持 Vue…

.vue 双向绑定实现原理

.vue 双向绑定实现原理

Vue 双向绑定实现原理 Vue 的双向绑定核心是通过数据劫持结合发布-订阅模式实现的,主要依赖以下技术: 数据劫持(Object.defineProperty 或 Proxy) Vue 2.x 使…

vue实现双向绑定模拟

vue实现双向绑定模拟

Vue 双向绑定模拟实现 Vue 的双向绑定核心是通过数据劫持结合发布-订阅模式实现。以下是一个简化版的模拟实现: 数据劫持(Object.defineProperty) 通过 Object…

vue绑定图片实现默认

vue绑定图片实现默认

vue绑定图片实现默认的方法 在Vue中绑定图片并设置默认图片,可以通过多种方式实现。以下是几种常见的方法: 使用v-bind绑定图片路径 在模板中使用v-bind指令绑定图片路径,同时设置默认图…

vue动态绑定实现原理

vue动态绑定实现原理

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

vue怎样实现双向绑定

vue怎样实现双向绑定

Vue 双向绑定的实现方式 Vue 主要通过 v-model 指令实现双向绑定,该指令在表单元素或自定义组件上创建双向数据绑定。以下是具体实现方法: 表单元素的双向绑定 在表单输入元素(如 inpu…