当前位置:首页 > VUE

vue双向实现

2026-01-11 21:37:32VUE

Vue 双向绑定的实现原理

Vue 的双向绑定主要通过 v-model 指令实现,底层结合了数据劫持(Object.definePropertyProxy)和发布-订阅模式。以下是核心实现机制:

数据劫持

Vue 2.x 使用 Object.defineProperty 劫持对象的属性访问和修改,Vue 3.x 改用 Proxy 实现更高效的数据监听。

Vue 2.x 示例:

const data = { text: '' };
Object.defineProperty(data, 'text', {
  get() {
    return this._text;
  },
  set(newVal) {
    this._text = newVal;
    console.log('数据更新了');
  }
});

Vue 3.x 示例:

const data = { text: '' };
const proxy = new Proxy(data, {
  get(target, key) {
    return target[key];
  },
  set(target, key, value) {
    target[key] = value;
    console.log('数据更新了');
    return true;
  }
});

发布-订阅模式

通过 Dep(依赖收集器)和 Watcher(观察者)实现数据变化时的视图更新:

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

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

v-model 的实现

v-model 是语法糖,本质上是 :value@input 的组合:

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

自定义双向绑定组件

通过 model 选项和 $emit 实现自定义组件的双向绑定:

子组件:

export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: ['value'],
  methods: {
    handleInput(e) {
      this.$emit('change', e.target.value);
    }
  }
}

父组件使用:

<custom-input v-model="text"></custom-input>

注意事项

  • Vue 2.x 中 Object.defineProperty 无法检测数组下标变化,需通过 Vue.set 或数组方法触发更新。
  • Vue 3.x 的 Proxy 支持深层监听,但需注意性能开销。
  • 复杂场景可结合 .sync 修饰符或 v-bind.sync 实现多属性双向绑定。

vue双向实现

标签: 双向vue
分享给朋友:

相关文章

前端vue登录功能实现

前端vue登录功能实现

Vue 登录功能实现步骤 创建登录表单组件 在 Vue 项目中创建一个登录组件,通常命名为 Login.vue。该组件包含用户名和密码输入框以及提交按钮。 <template> &l…

vue实现横向导航

vue实现横向导航

vue实现横向导航的方法 使用Flex布局实现横向导航 在Vue中可以通过Flex布局快速实现横向导航。创建一个组件,使用display: flex和flex-direction: row属性使导航项…

vue实现视频会议

vue实现视频会议

使用 Vue 实现视频会议 技术选型 Vue.js 作为前端框架,结合 WebRTC 技术实现实时音视频通信。常用的库包括: peerjs:简化 WebRTC 的点对点连接。 socket.io:用…

vue实现关键词轮播

vue实现关键词轮播

Vue 实现关键词轮播 基础实现方案 使用 Vue 的 v-for 和 setInterval 实现基础轮播效果: <template> <div class="keywor…

vue实现密码框的包

vue实现密码框的包

Vue 密码框实现方案 在 Vue 中实现密码框功能,可以通过原生 HTML 结合 Vue 指令或使用第三方组件库完成。以下是几种常见方案: 原生 HTML + Vue 双向绑定 <t…

vue全选实现

vue全选实现

Vue 全选实现方法 在 Vue 中实现全选功能通常涉及数据绑定和事件处理。以下是几种常见的实现方式: 基础实现方式 <template> <div> <…