当前位置:首页 > VUE

vue实现双向绑定

2026-02-09 09:52:56VUE

Vue 实现双向绑定的原理

Vue 的双向绑定主要通过 v-model 指令实现,其底层依赖 Object.defineProperty(Vue 2.x)或 Proxy(Vue 3.x)进行数据劫持和发布-订阅模式。

基于 Object.defineProperty(Vue 2.x)

在 Vue 2.x 中,双向绑定的核心是通过 Object.defineProperty 劫持数据的 gettersetter,结合观察者模式实现数据与视图的同步。

// 简化版数据劫持示例
function defineReactive(obj, key, val) {
  Object.defineProperty(obj, key, {
    get() {
      console.log(`读取 ${key}: ${val}`);
      return val;
    },
    set(newVal) {
      if (newVal !== val) {
        console.log(`设置 ${key}: ${newVal}`);
        val = newVal;
        // 触发视图更新
      }
    }
  });
}

const data = {};
defineReactive(data, 'message', 'Hello Vue');
data.message = 'Updated'; // 触发 setter

基于 Proxy(Vue 3.x)

Vue 3.x 改用 Proxy 实现响应式,解决了 Object.defineProperty 无法监听数组和对象新增属性的问题。

// 简化版 Proxy 实现
const reactive = (target) => {
  return new Proxy(target, {
    get(target, key) {
      console.log(`读取 ${key}: ${target[key]}`);
      return target[key];
    },
    set(target, key, value) {
      if (target[key] !== value) {
        console.log(`设置 ${key}: ${value}`);
        target[key] = value;
        // 触发视图更新
      }
      return true;
    }
  });
};

const data = reactive({ message: 'Hello Vue 3' });
data.message = 'Updated'; // 触发 set

v-model 的实现

v-model 是语法糖,本质上是 :value@input 的组合。以输入框为例:

<input v-model="message" />
<!-- 等价于 -->
<input :value="message" @input="message = $event.target.value" />

自定义组件实现双向绑定

在自定义组件中,可以通过 model 选项和 $emit 实现双向绑定:

<custom-input v-model="message"></custom-input>
Vue.component('custom-input', {
  props: ['value'],
  model: {
    prop: 'value',
    event: 'input'
  },
  template: `
    <input 
      :value="value" 
      @input="$emit('input', $event.target.value)"
    />
  `
});

响应式系统的依赖收集

Vue 通过 Dep(依赖管理器)和 Watcher(观察者)实现依赖收集和派发更新:

  1. 依赖收集:在 getter 中调用 dep.depend(),将当前 Watcher 添加到 Dep 中。
  2. 派发更新:在 setter 中调用 dep.notify(),通知所有 Watcher 更新视图。
class Dep {
  constructor() {
    this.subs = [];
  }
  depend() {
    if (Dep.target) {
      this.subs.push(Dep.target);
    }
  }
  notify() {
    this.subs.forEach(watcher => watcher.update());
  }
}
Dep.target = null;

数组的响应式处理

Vue 2.x 通过重写数组的变异方法(如 pushpop)实现响应式:

vue实现双向绑定

const arrayProto = Array.prototype;
const arrayMethods = Object.create(arrayProto);
['push', 'pop', 'shift'].forEach(method => {
  const original = arrayProto[method];
  arrayMethods[method] = function(...args) {
    const result = original.apply(this, args);
    console.log(`数组方法 ${method} 被调用`);
    // 触发视图更新
    return result;
  };
});

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

相关文章

vue实现双休绑定

vue实现双休绑定

Vue 实现双向绑定 Vue.js 通过 v-model 指令实现双向绑定,主要用于表单输入元素(如 <input>、<textarea>、<select>)与组件…

vue实现数据双向

vue实现数据双向

在Vue中实现数据双向绑定主要依靠v-model指令,它结合了属性绑定和事件监听,适用于表单元素或自定义组件。以下是具体实现方式: 基础表单元素的双向绑定 对于原生表单元素(如input、texta…

实现vue数据绑定

实现vue数据绑定

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

vue双向绑定如何实现

vue双向绑定如何实现

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

vue如何实现数据绑定

vue如何实现数据绑定

Vue 数据绑定的实现方式 Vue 的数据绑定主要通过双向绑定(v-model)和单向绑定({{ }}插值或 v-bind)实现,核心基于响应式系统。以下是具体实现方法: 插值绑定(单向) 使用双大…

实现Vue双向数据绑定

实现Vue双向数据绑定

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