vue3使用reactive包裹数组如何正确赋值

 

需求:将接口请求到的列表数据赋值给响应数据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])

这几种办法都可以触发响应性,推荐第一种

原文地址:https://www.cnblogs.com/onesea/p/15683938.html