Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

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数组的响应性?
  • 如何方便的将整个数组拼接到响应式数据上?

代码地址↓
https://codesandbox.io/s/prac...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

我给你提供几种办法

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])

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...