Vue3中如何正确使用`ref`和`reactive`来声明响应式数据,它们有什么区别?

**In Vue 3**, both `ref` and `reactive` are used to create reactive data, yet they differ in their use scenarios and implementation: --- ### **Core Differences** - `ref` wraps its internal value with `reactive` to form a `{ value: ... }` object, but retains the underlying `reactive` object, adding only a single layer of encapsulation. - `reactive` uses Proxy to proxy the original object, and is specifically applicable to reference types (objects, arrays), but cannot be directly assigned values. --- ### **Usage Scenarios** 1. **Basic Types** - **Applicable**: Basic types such as strings, numbers, booleans. - **Example**: ```js const count = ref(0); // Modify value via `count.value` ``` 2. **Objects/Arrays** - **Applicable**: Objects or arrays. - **Example**: ```js const state = reactive({ count: 0 }); // Directly modify `state.count` ``` --- ### **Usage Guidelines** 1. **Assignment Restrictions** - `reactive` cannot reassign the entire variable (e.g., `state = {}`), which would lose reactivity. - `ref` can safely reassign values via `.value`. 2. **Destructuring and Reactivity** - Destructuring a `reactive` object loses reactivity; use `toRefs` to retain it: ```js import { toRefs } from 'vue' const { count } = toRefs(state) ``` 3. **Template Automatic Unpacking** - `ref` is automatically unpacked in templates, allowing direct use of `{{ count }}` without explicit `.value` calls. --- ### **Summary** - **Basic Types**: Use `ref` (easier for function returns or parameter passing). - **Objects/Arrays**: Use `reactive` (recommended for complex structures), or still use `ref` (higher flexibility). - **Composition Functions**: `ref` offers greater flexibility when returning reactive data.