当前位置:首页 > 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 无法监听数组和对象新增属性的问题。

vue实现双向绑定

// 简化版 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 实现双向绑定:

vue实现双向绑定

<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)实现响应式:

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

vue实现绑定herf

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

vue 绑定实现

vue 绑定实现

Vue 数据绑定实现 Vue 的数据绑定主要通过响应式系统和模板编译实现,以下是核心实现方式: 双向绑定 (v-model) 适用于表单元素,自动同步输入值与 Vue 实例数据: <in…

vue实现数组绑定

vue实现数组绑定

Vue 数组绑定的实现方法 Vue 提供了多种方式实现数组的响应式绑定,确保数据变化时视图自动更新。以下是常见的实现方法: 使用 v-for 指令渲染数组 通过 v-for 指令可以遍历数组并…

vue实现双休绑定

vue实现双休绑定

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

vue双向实现原理

vue双向实现原理

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

vue实现数据双向

vue实现数据双向

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