在 Vue 3 中,監聽一個?Ref
?類型的數字數組(如?ref<number[]>([])
)時,根據需求的不同,有幾種監聽方式:
1.?監聽整個數組的引用變化
當整個數組被重新賦值時觸發:
typescript
復制
下載
import { ref, watch } from 'vue';const numbers = ref<number[]>([1, 2, 3]);watch(numbers, (newVal, oldVal) => {console.log('數組被替換:', newVal, oldVal); });
2.?監聽數組內部元素的變化(深度監聽)
當數組內部元素被修改(增/刪/改)時觸發:
typescript
復制
下載
watch(numbers, (newVal) => {console.log('數組內部變化:', newVal); }, { deep: true }); // 關鍵:啟用深度監聽
3.?使用?watchEffect
?自動跟蹤依賴
自動響應數組及其內部元素的變化:
typescript
復制
下載
import { watchEffect } from 'vue';watchEffect(() => {console.log('當前數組內容:', numbers.value); });
4.?監聽特定索引的元素
只關注數組中某個索引位置的變化:
typescript
復制
下載
watch(() => numbers.value[0], // 監聽索引 0 的元素(newVal, oldVal) => {console.log('第一個元素變化:', newVal, oldVal);} );
5.?監聽數組長度變化
只關注數組長度的變化:
typescript
復制
下載
watch(() => numbers.value.length,(newLen, oldLen) => {console.log(`數組長度變化: ${oldLen} -> ${newLen}`);} );
完整示例代碼
vue
復制
下載
<script setup lang="ts"> import { ref, watch, watchEffect } from 'vue';const numbers = ref<number[]>([1, 2, 3]);// 1. 監聽整個數組引用 watch(numbers, (newVal, oldVal) => {console.log('數組引用變化:', { newVal, oldVal }); });// 2. 深度監聽內部元素 watch(numbers, (newVal) => {console.log('深度監聽內部變化:', newVal); }, { deep: true });// 3. 自動跟蹤依賴 watchEffect(() => {console.log('watchEffect 觸發:', numbers.value); });// 4. 監聽特定索引 watch(() => numbers.value[0],(newVal, oldVal) => {console.log('索引 0 變化:', { newVal, oldVal });} );// 5. 監聽數組長度 watch(() => numbers.value.length,(newLen, oldLen) => {console.log('長度變化:', { newLen, oldLen });} );// 測試方法 const changeArray = () => {numbers.value.push(4); // 觸發深度監聽、watchEffect、長度監聽 };const replaceArray = () => {numbers.value = [10, 20]; // 觸發引用監聽、深度監聽、watchEffect };const updateElement = () => {numbers.value[0] = 100; // 觸發深度監聽、watchEffect、特定索引監聽 }; </script><template><div><p>數組內容: {{ numbers }}</p><button @click="changeArray">Push 新元素</button><button @click="replaceArray">替換整個數組</button><button @click="updateElement">修改第一個元素</button></div> </template>
關鍵注意事項:
-
深度監聽?
{ deep: true }
必須顯式開啟才能檢測數組內部變化(如?push
、splice
?或直接修改索引值)。 -
引用變化 vs 內部變化
-
重新賦值整個數組(
numbers.value = [...]
)會觸發引用變化。 -
修改數組內部元素(
numbers.value[0] = 100
?或?push()
)需要深度監聽。
-
-
watchEffect
?的自動依賴
在回調中使用到的響應式變量(如?numbers.value
)會被自動跟蹤,無需聲明依賴。
根據你的具體場景選擇合適的監聽方式即可。