当前位置:首页 > VUE

vue3实现reactive

2026-02-25 03:22:26VUE

Vue 3 实现 reactive

Vue 3 的 reactive 是 Composition API 的核心功能之一,用于创建响应式对象。以下是实现 reactive 的几种方法:

使用 reactive 函数

通过 reactive 函数可以将普通对象转换为响应式对象。响应式对象的所有嵌套属性也会自动成为响应式的。

import { reactive } from 'vue';

const state = reactive({
  count: 0,
  user: {
    name: 'John',
    age: 25
  }
});

// 修改响应式对象
state.count++;
state.user.name = 'Jane';

使用 refreactive 结合

ref 用于包装基本类型(如数字、字符串等),而 reactive 用于包装对象。两者可以结合使用。

import { reactive, ref } from 'vue';

const count = ref(0);
const state = reactive({
  count,
  user: {
    name: 'John'
  }
});

// 修改 ref 或 reactive 对象
count.value++;
state.user.name = 'Jane';

响应式对象的解构问题

直接解构 reactive 对象会失去响应性。需要使用 toRefstoRef 保持响应性。

import { reactive, toRefs } from 'vue';

const state = reactive({
  count: 0,
  name: 'John'
});

// 使用 toRefs 解构保持响应性
const { count, name } = toRefs(state);

// 修改解构后的属性
count.value++;
name.value = 'Jane';

嵌套对象的响应性

reactive 会自动处理嵌套对象的响应性,无需额外操作。

const state = reactive({
  user: {
    profile: {
      age: 25
    }
  }
});

// 修改嵌套属性
state.user.profile.age++;

watch 结合使用

可以通过 watch 监听 reactive 对象的变化。

import { reactive, watch } from 'vue';

const state = reactive({
  count: 0
});

watch(() => state.count, (newValue, oldValue) => {
  console.log(`Count changed from ${oldValue} to ${newValue}`);
});

state.count++; // 触发 watch

computed 结合使用

可以通过 computed 创建基于 reactive 对象的计算属性。

import { reactive, computed } from 'vue';

const state = reactive({
  firstName: 'John',
  lastName: 'Doe'
});

const fullName = computed(() => `${state.firstName} ${state.lastName}`);

console.log(fullName.value); // "John Doe"

注意事项

  • reactive 只能用于对象或数组,基本类型需使用 ref
  • 直接替换 reactive 对象会失去响应性,应通过修改属性实现更新。
  • 解构 reactive 对象时需使用 toRefstoRef 保持响应性。

以上方法涵盖了 reactive 的基本用法和常见场景,可根据需求选择合适的方式实现响应式数据管理。

vue3实现reactive

标签: reactive
分享给朋友: