需求:將接口請求到的列表數據賦值給響應數據arr
const arr = reactive([]); const load = () => { const res = [2, 3, 4, 5]; //假設請求接口返回的數據 // 方法1 失敗,直接賦值丟失了響應性 // arr = res; // 方法2 這樣也是失敗 // arr.concat(res); // 方法3 可以,但是很麻煩 res.forEach(e => { arr.push(e); }); };
vue3使用proxy
,對於對象和數組都不能直接整個賦值。
使用方法1能理解,直接賦值給用reactive
包裹的對象也不能這么做。
方法2為什么不行?
只有push或者根據索引遍歷賦值才可以保留reactive數組的響應性?
如何方便的將整個數組拼接到響應式數據上?
提供幾種辦法
const state = reactive({ arr: [] }); state.arr = [1, 2, 3] 或者 const state = ref([]) state.value = [1, 2, 3] 或者 const arr = reactive([]) arr.push(...[1, 2, 3])