当前位置:首页 > VUE

vue双向绑定实现

2026-02-19 20:33:05VUE

Vue 双向绑定的实现原理

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

数据劫持(响应式原理)

Vue 2.x 使用 Object.defineProperty 通过递归遍历数据对象的属性,将其转换为 getter/setter,在属性被访问或修改时触发依赖收集和更新。

function defineReactive(obj, key, val) {
  Object.defineProperty(obj, key, {
    get() {
      console.log(`读取 ${key}`);
      return val;
    },
    set(newVal) {
      if (newVal === val) return;
      console.log(`更新 ${key}`);
      val = newVal;
      // 触发视图更新
    },
  });
}

Vue 3.x 使用 Proxy Proxy 直接代理整个对象,无需递归遍历,性能更好且支持动态新增属性。

function reactive(obj) {
  return new Proxy(obj, {
    get(target, key) {
      console.log(`读取 ${key}`);
      return Reflect.get(target, key);
    },
    set(target, key, newVal) {
      if (newVal === target[key]) return true;
      console.log(`更新 ${key}`);
      Reflect.set(target, key, newVal);
      // 触发视图更新
      return true;
    },
  });
}

依赖收集与派发更新

Dep(依赖管理器): 每个响应式属性对应一个 Dep 实例,用于存储依赖(Watcher)。

class Dep {
  constructor() {
    this.subscribers = new Set();
  }
  depend() {
    if (currentWatcher) {
      this.subscribers.add(currentWatcher);
    }
  }
  notify() {
    this.subscribers.forEach(watcher => watcher.update());
  }
}

Watcher(订阅者): 在组件渲染时创建,负责执行更新逻辑(如重新渲染)。

class Watcher {
  constructor(updateFn) {
    this.updateFn = updateFn;
    this.update();
  }
  update() {
    currentWatcher = this;
    this.updateFn();
    currentWatcher = null;
  }
}

双向绑定的实现

模板编译: Vue 将模板编译为渲染函数,解析 v-model 指令,生成对应的数据绑定和事件监听。

v-model 示例:

<input v-model="message">

等价于:

vue双向绑定实现

<input 
  :value="message" 
  @input="message = $event.target.value"
>

完整流程

  1. 初始化阶段: 通过数据劫持监听数据变化。
  2. 编译阶段: 解析模板,为每个绑定创建 Watcher。
  3. 依赖收集: 在首次渲染时触发 getter,将 Watcher 添加到 Dep 中。
  4. 更新阶段: 数据变化时触发 setter,调用 Dep.notify() 通知所有 Watcher 更新视图。

注意事项

  • 性能优化: Vue 3.x 的 Proxy 避免了 Vue 2.x 中递归遍历和无法监听新增属性的问题。
  • 数组处理: Vue 2.x 需重写数组方法(如 pushpop)以实现响应式。

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

相关文章

vue样式绑定实现收藏

vue样式绑定实现收藏

Vue 样式绑定实现收藏功能 在 Vue 中,可以通过动态绑定样式来实现收藏功能,常见的方法是使用 v-bind:class 或 v-bind:style 来切换样式状态。 使用 v-bind:cl…

vue数据实现双向绑定

vue数据实现双向绑定

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

jquery事件绑定

jquery事件绑定

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

vue 实现循环绑定

vue 实现循环绑定

Vue 实现循环绑定的方法 在 Vue 中,可以通过 v-for 指令实现循环绑定,用于渲染列表或对象数据。以下是几种常见的实现方式: 数组循环绑定 使用 v-for 遍历数组,可以通过索引或直接获…

实现vue数组双向绑定

实现vue数组双向绑定

Vue 数组双向绑定的实现方法 Vue 通过数据劫持和发布-订阅模式实现数据的双向绑定,但直接修改数组的某些方法(如索引赋值)无法触发视图更新。以下是实现数组双向绑定的几种方法: 使用 Vue.se…

vue双向绑定如何实现

vue双向绑定如何实现

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