在 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/)
?