在 Vue 3 中,响应式系统进行了全新设计,`ref` 和 `reactive` 是其中的核心概念。
### 一、ref 的使用
`ref` 适用于基本数据类型,也可以用于对象,但返回的是一个带 `.value` 的包装对象。
```js
import { ref } from 'vue'
const count = ref(0)
count.value++
```
### 二、reactive 的使用
`reactive` 适用于复杂对象,如对象、数组等,返回的对象就是响应式的代理本体:
```js
import { reactive } from 'vue'
const state = reactive({ count: 0 })
state.count++
```
### 三、使用区别
- ref 更适用于原始值(number、string等),结合模板语法
- reactive 适用于复杂嵌套结构
### 四、注意事项
- reactive 无法嵌套 ref,嵌套时需使用 `toRefs`
- reactive 创建出的对象不能解构,否则会失去响应性
掌握这两个响应式工具,是写好 Vue 3 项目的基础。
👉 想 Vue 实战内容,欢迎访问 [码农资讯网](https://www.codesou.cn/)