目錄
1. 前言
前兩天在工作當中遇到一個問題,在vue3中使用reactive生成的響應式數組如何清空,當然我一般清空都是這么寫:
let array = [1,2,3];
array = [];
不過這么用在reactive代理的方式中還是有點問題,比如這樣:
let array = reactive([1,2,3]); watch(()=>[...array],()=>{ console.log(array); },) array = reactive([]);
很顯然,因為丟失了對原來響應式對象的引用,這樣就直接失去了監聽。
2. 清空數據的幾種方式
當然,作為常年摸魚的我,立馬就給出了幾個解決方案。
2.1 使用ref()
使用ref,這是最簡便的方法:
const array = ref([1,2,3]);//data區域 //watch監聽 watch(array,()=>{ console.log(array.value); },) array.value = [];//清空的方法
2.2 使用slice
slice顧名思義,就是對數組進行切片,然后返回一個新數組,感覺和go語言的切片有點類似。當然用過react的小伙伴應該經常用slice,清空一個數組只需要這樣寫:
const array = ref([1,2,3]); watch(array,()=>{ console.log(array.value); },) array.value = array.value.slice(0,0);

不過需要注意要使用ref。
2.3 length賦值為0
個人比較喜歡這種,直接將length賦值為0:
const array = ref([1,2,3]); watch(array,()=>{ console.log(array.value); },{ deep:true }) array.value.length = 0;
而且,這種只會觸發一次,但是需要注意watch要開啟deep:

不過,這種方式,使用reactive會更加方便,也不用開啟deep:
const array = reactive([1,2,3]); watch(()=>[...array],()=>{ console.log(array); }) array.length = 0;

2.4 使用splice
副作用函數splice也是一種方案,這種情況同時也可以使用reactive:
const array = reactive([1,2,3]); watch(()=>[...array],()=>{ console.log(array); },) array.splice(0,array.length)
不過要注意,watch會觸發多次:

當然也可以使用ref,但是注意這種情況下,需要開啟deep:
const array = ref([1,2,3]); watch(array,()=>{ console.log(array.value); },{ deep:true }) array.value.splice(0,array.value.length)

但是可以看到ref也和reactive一樣,會觸發多次。
3. 總結
到此這篇關於vue清空數組的幾個方式(小結)的文章就介紹到這了,更多相關vue清空數組內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
4.Vue提供了如下的數組的變異方法,可以觸發視圖更新
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
轉 : https://www.jb51.net/article/233232.htm

