前言
在 Vue 3 中,ref
和 reactive
是兩種用來建立響應式數據的方法。雖然它們的功能相似,但使用方式和適用場景有所不同。本文將簡單介紹它們的差異和使用方法。
ref
ref
用於創建單一基本數據類型(如字符串、數字、布林值)或對象的響應式引用。當你需要一個單一的數據值時,使用 ref
是最合適的選擇。
使用範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <script setup> import { ref } from 'vue';
const textRef = ref('Hello, Vue 3 ref!'); const booleanRef = ref(true); const arrayRef = ref([1, 2, 3, 4, 5]); const objRef = ref({ name: 'Vue 3', version: '3.0.0', });
console.log('textRef: ', textRef); console.log('booleanRef: ', booleanRef); console.log('arrayRef: ', arrayRef); console.log('objRef: ', objRef); console.log('------------------------------- 分隔線 -------------------------------'); console.log('textRef: ', textRef.value); console.log('booleanRef: ', booleanRef.value); console.log('arrayRef: ', arrayRef.value); console.log('arrayRef[0]: ', arrayRef.value[0]); console.log('objRef: ', objRef.value); console.log('objRef name: ', objRef.value.name); </script>
|

小結
如上圖所示,ref
的使用方式簡單明瞭,並且能處理多種類型的數據。
reactive
reactive
用於創建響應式數據對象,特別適合用於複雜數據結構,讓管理多個屬性變得更加簡便。
使用範例
1 2 3 4 5 6 7 8 9 10
| <script setup> import { reactive } from 'vue';
const state = reactive({ message: 'Hello, Vue 3 reactive!', });
console.log('State:', state); console.log('Message:', state.message); </script>
|

小結
使用 reactive
可以有效地管理複雜對象的響應性,並可通過對象的屬性直接訪問數據。需要注意的是,使用解構賦值會導致響應性失效,而使用 let
宣告的 reactive
物件如果被直接覆蓋,將會恢復為原本的物件格式,進而失去響應性。
總結
以下是 ref
和 reactive
的對比:
|
ref |
reactive |
接收型別 |
所有型別 |
物件型別 |
回傳結果 |
RefImpl 物件 |
Proxy 物件 |
如何取值 |
需透過 .value |
直接訪問屬性 |
透過以上的介紹和範例,你應該能夠更好地理解 ref
和 reactive
的用法及其適用場景。希望這篇文章對你學習 Vue 3 有所幫助!