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

失败的方法

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);
  });
};

正确的方法

方法一:

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://segmentfault.com/q/1010000038701322

原文地址:https://www.cnblogs.com/ziyoublog/p/14914388.html