Vue 3 中如何正确使用 ref 和 reactive 的区别是什么?
Author: 图恩Category: 编程开发Views: 165Published: 2025-11-08 **Question:** What is the difference between using `ref` and `reactive` in Vue 3?
**Answer:**
In Vue 3, both `ref` and `reactive` are used to create reactive data, but they differ in usage and context:
- **`ref`**
- Used to wrap basic types (e.g., `string`, `number`, `boolean`) or objects into reactive references.
- Values must be accessed via `.value` (in `setup()` functions), but can be directly used in templates (Vue automatically unwraps them).
- Example:
```js
const count = ref(0);
console.log(count.value); // 0
count.value++; // Updates the actual value
```
- **`reactive`**
- Specifically for creating reactive proxies for object types (e.g., plain objects, arrays).
- Implements deep reactivity via ES6 Proxy.
- Cannot be used for basic types, and proxies entire objects without `.value`.
- Example:
```js
const state = reactive({ name: 'Alice', age: 25 });
console.log(state.name); // Alice
state.age = 26; // Updates all nested properties
```
**Key Differences:**
- **Data Type:**
- `ref` handles basic types (e.g., numbers, strings).
- `reactive` is for objects/arrays, requiring full proxying.
- **Template Usage:**
- `ref` is automatically unwrapped in templates, so `{{ count }}` works directly.
- `reactive` objects require explicit unwrapping with `toRefs` when destructured.
**Best Practices:**
- Use `ref` for raw values (e.g., numbers, strings).
- Use `reactive` for objects/arrays to enable deep reactivity.
- `reactive` objects are "deeply reactive" by default, while `ref` wraps objects internally (e.g., `ref({})` is equivalent to `ref(reactive({}))`).
**Recommendation:**
Choose `ref` for general-purpose use in Vue Composition APIs due to its broader applicability.
---
This translation maintains technical accuracy while ensuring clarity and professional tone. The structure adheres to Vue's documentation style, emphasizing distinctions between the two APIs.