当前位置:首页 > VUE

vue数据劫持实现

2026-01-08 06:51:03VUE

Vue 数据劫持的实现原理

Vue 的数据劫持主要通过 Object.definePropertyProxy 实现,用于监听数据变化并触发视图更新。以下是核心实现方式:

使用 Object.defineProperty

Object.defineProperty 是 Vue 2.x 的核心实现方式,通过劫持对象的属性访问和修改。

vue数据劫持实现

function defineReactive(obj, key, val) {
  // 递归处理嵌套对象
  observe(val);

  Object.defineProperty(obj, key, {
    get() {
      console.log(`读取 ${key}: ${val}`);
      return val;
    },
    set(newVal) {
      if (newVal !== val) {
        console.log(`设置 ${key}: ${newVal}`);
        observe(newVal); // 对新值进行劫持
        val = newVal;
      }
    }
  });
}

function observe(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return;
  }
  Object.keys(obj).forEach(key => {
    defineReactive(obj, key, obj[key]);
  });
}

// 示例
const data = { foo: 'bar' };
observe(data);
data.foo; // 触发 getter
data.foo = 'baz'; // 触发 setter

使用 Proxy

Vue 3.x 改用 Proxy 实现数据劫持,能直接监听整个对象而非逐个属性。

function reactive(obj) {
  return new Proxy(obj, {
    get(target, key) {
      console.log(`读取 ${key}: ${target[key]}`);
      return target[key];
    },
    set(target, key, newVal) {
      if (target[key] !== newVal) {
        console.log(`设置 ${key}: ${newVal}`);
        target[key] = newVal;
      }
      return true;
    }
  });
}

// 示例
const data = reactive({ foo: 'bar' });
data.foo; // 触发 get
data.foo = 'baz'; // 触发 set

差异对比

  • Object.defineProperty
    需遍历对象属性逐个劫持,无法监听新增/删除属性(需配合 Vue.set/Vue.delete)。

    vue数据劫持实现

  • Proxy
    直接代理整个对象,支持监听新增/删除属性,性能更优,但兼容性较低(IE 不支持)。

实现依赖收集

数据劫持需结合发布-订阅模式,在 getter 中收集依赖(Watcher),在 setter 中通知更新。

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

let currentWatcher = null;

function watchEffect(fn) {
  currentWatcher = fn;
  fn();
  currentWatcher = null;
}

// 修改 defineReactive 加入依赖收集
function defineReactive(obj, key, val) {
  const dep = new Dep();
  observe(val);
  Object.defineProperty(obj, key, {
    get() {
      dep.depend();
      return val;
    },
    set(newVal) {
      if (newVal !== val) {
        observe(newVal);
        val = newVal;
        dep.notify();
      }
    }
  });
}

通过以上方式,Vue 实现了数据变化到视图更新的自动响应。

标签: 数据vue
分享给朋友:

相关文章

vue实现钟表

vue实现钟表

使用 Vue 实现动态钟表 以下是一个基于 Vue 3 的动态钟表实现方案,包含时分秒指针和数字时间显示。 模板部分 <template> <div class="cloc…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router 通…

vue 实现modal

vue 实现modal

Vue 实现 Modal 的方法 使用 Vue 原生组件 通过 Vue 的组件系统可以轻松实现 Modal。创建一个可复用的 Modal 组件,通过 props 控制显示与隐藏。 <templ…

vue实现slot

vue实现slot

Vue 中的 Slot 实现方法 Vue 的 slot 是一种内容分发机制,允许父组件向子组件插入内容。以下是几种常见的 Slot 实现方式: 默认 Slot 子组件通过 <slot>…

vue 实现报价

vue 实现报价

Vue 实现报价功能 在 Vue 中实现报价功能通常涉及前端表单交互、数据计算和与后端 API 的通信。以下是实现报价功能的几种常见方法: 表单设计与数据绑定 使用 Vue 的 v-model 指…

黑马vue实现

黑马vue实现

以下是关于使用 Vue.js 实现黑马相关功能或项目的关键方法和实践指南: 环境配置与项目初始化 安装最新版 Vue CLI 或使用 Vite 创建项目: npm create vue@lates…