当前位置:首页 > VUE

vue双向绑定的实现

2026-01-22 00:17:35VUE

Vue 双向绑定的实现原理

Vue 的双向绑定是通过数据劫持结合发布者-订阅者模式实现的,核心是 Object.defineProperty(Vue 2.x)或 Proxy(Vue 3.x)。

数据劫持

在 Vue 2.x 中,使用 Object.defineProperty 对对象的属性进行劫持,监听属性的读取和修改操作。

function defineReactive(obj, key, val) {
  Object.defineProperty(obj, key, {
    get() {
      console.log(`读取 ${key}`);
      return val;
    },
    set(newVal) {
      if (newVal === val) return;
      console.log(`设置 ${key} 为 ${newVal}`);
      val = newVal;
    }
  });
}

依赖收集

每个被劫持的属性都有一个对应的 Dep 实例,用于收集依赖(Watcher)。当属性被读取时,当前的 Watcher 会被添加到 Dep 中。

class Dep {
  constructor() {
    this.subscribers = [];
  }
  depend() {
    if (target && !this.subscribers.includes(target)) {
      this.subscribers.push(target);
    }
  }
  notify() {
    this.subscribers.forEach(sub => sub());
  }
}

观察者模式

Watcher 是一个观察者,当数据变化时,Dep 会通知所有 Watcher 更新视图。

let target = null;
class Watcher {
  constructor(vm, key, cb) {
    target = this;
    this.vm = vm;
    this.key = key;
    this.cb = cb;
    this.value = vm[key]; // 触发 getter,收集依赖
    target = null;
  }
  update() {
    this.value = this.vm[this.key];
    this.cb.call(this.vm, this.value);
  }
}

模板编译

Vue 的模板编译器会将模板中的指令(如 v-model)解析为对应的数据绑定和事件监听。

function compile(node, vm) {
  if (node.nodeType === 1) {
    const attrs = node.attributes;
    for (let i = 0; i < attrs.length; i++) {
      if (attrs[i].nodeName === 'v-model') {
        const name = attrs[i].nodeValue;
        node.addEventListener('input', e => {
          vm[name] = e.target.value;
        });
        node.value = vm[name];
        node.removeAttribute('v-model');
      }
    }
  }
}

Vue 3 的 Proxy 实现

Vue 3 使用 Proxy 替代 Object.defineProperty,可以直接监听对象而非属性,支持数组变化检测。

function reactive(obj) {
  return new Proxy(obj, {
    get(target, key) {
      console.log(`读取 ${key}`);
      return target[key];
    },
    set(target, key, value) {
      if (target[key] === value) return true;
      console.log(`设置 ${key} 为 ${value}`);
      target[key] = value;
      return true;
    }
  });
}

双向绑定的实现步骤

  1. 数据劫持:通过 Object.definePropertyProxy 监听数据变化。
  2. 依赖收集:在 getter 中收集依赖,setter 中通知更新。
  3. 模板编译:解析模板中的指令,建立数据与视图的关联。
  4. 观察者模式:Watcher 作为桥梁,连接数据变化和视图更新。

注意事项

  • Vue 2.x 无法检测到对象属性的添加或删除,需使用 Vue.setVue.delete
  • Vue 3 的 Proxy 可以监听整个对象,无需特殊处理动态属性。
  • 双向绑定是 v-model 的语法糖,本质是 :value@input 的组合。

vue双向绑定的实现

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

相关文章

vue 绑定实现

vue 绑定实现

Vue 绑定实现 Vue 提供了多种数据绑定的方式,包括文本插值、属性绑定、事件绑定、双向绑定等。以下是常见的绑定实现方法: 文本插值 使用双大括号 {{ }} 进行文本插值,将数据动态渲染到 D…

vue双向实现数据

vue双向实现数据

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

vue实现事件绑定的是

vue实现事件绑定的是

Vue 事件绑定实现方式 Vue 通过 v-on 指令实现事件绑定,语法为 v-on:事件名="处理方法" 或简写为 @事件名="处理方法"。以下是具体实现方法和示例: 基础事件绑定 <bu…

vue数据实现双向绑定

vue数据实现双向绑定

Vue 数据双向绑定的实现原理 Vue 的数据双向绑定主要通过 v-model 指令实现,结合了数据绑定和事件监听。以下是核心实现方式: 使用 v-model 指令 v-model 是语法糖,自动绑…

react如何绑定事件

react如何绑定事件

React 事件绑定方法 在 React 中绑定事件有多种方式,以下是常见的几种方法: 使用 onClick 或其他事件属性直接绑定 <button onClick={() => co…

jquery事件绑定

jquery事件绑定

jQuery 事件绑定的基本方法 使用 on() 方法绑定事件是最推荐的方式,兼容性强且支持动态元素。语法如下: $(selector).on(eventName, handlerFunction…