当前位置:首页 > VUE

vue-model实现

2026-01-18 08:37:35VUE

Vue 双向数据绑定实现原理

Vue 的双向数据绑定主要通过 v-model 指令实现,其核心是基于数据劫持和发布-订阅模式。

数据劫持

Vue 使用 Object.defineProperty 或 ES6 的 Proxy 来劫持对象的属性,当属性被访问或修改时触发相应的 getter 和 setter。

// 使用 Object.defineProperty 实现数据劫持
function defineReactive(obj, key, val) {
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter() {
      console.log(`获取 ${key}: ${val}`);
      return val;
    },
    set: function reactiveSetter(newVal) {
      console.log(`设置 ${key}: ${newVal}`);
      val = newVal;
    }
  });
}

发布-订阅模式

Vue 通过 Dep 和 Watcher 实现发布-订阅模式,Dep 用于收集依赖,Watcher 用于更新视图。

vue-model实现

class Dep {
  constructor() {
    this.subs = [];
  }
  addSub(sub) {
    this.subs.push(sub);
  }
  notify() {
    this.subs.forEach(sub => sub.update());
  }
}

class Watcher {
  update() {
    console.log('视图更新');
  }
}

v-model 实现

v-model 本质上是语法糖,结合了 v-bindv-on。以 input 元素为例:

<input v-model="message">

等价于:

vue-model实现

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

自定义组件实现 v-model

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

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

使用 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) {
      console.log(`设置 ${key}`);
      target[key] = value;
      return true;
    }
  });
}

总结

Vue 的双向数据绑定通过数据劫持和发布-订阅模式实现,v-model 是其语法糖形式。自定义组件可以通过 model 选项和 $emit 实现类似功能。Vue 3 使用 Proxy 提供了更强大的数据劫持能力。

标签: vuemodel
分享给朋友:

相关文章

vue实现autocomplete

vue实现autocomplete

Vue 实现 Autocomplete 功能 Vue 中实现 Autocomplete(自动完成)功能可以通过自定义组件或使用现有库完成。以下是几种常见方法: 方法一:使用 Vue 原生实现…

vue实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…

vue实现picker

vue实现picker

Vue 实现 Picker 组件的方法 在 Vue 中实现 Picker 组件可以通过多种方式完成,以下是几种常见的实现方法: 使用原生 HTML 和 CSS 实现 通过 Vue 的模板和样式绑定…

vue实现注册

vue实现注册

Vue 实现注册功能 注册功能通常涉及前端表单、数据验证、与后端 API 的交互等步骤。以下是一个完整的 Vue 实现注册功能的方案。 创建注册表单 使用 Vue 的模板语法创建注册表单,包含用户名…

vue实现表单

vue实现表单

Vue 表单实现方法 双向数据绑定 使用 v-model 指令实现表单元素与数据的双向绑定。适用于 input、textarea、select 等元素。 <template> &l…

vue 实现vshow

vue 实现vshow

Vue 实现 v-show 在 Vue 中,v-show 是一个常用的指令,用于根据条件控制元素的显示或隐藏。与 v-if 不同,v-show 不会移除 DOM 元素,而是通过 CSS 的 displ…