3

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

 3 years ago
source link: https://www.joynop.com/p/412.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

vue3使用proxy,对于对象和数组都不能直接整个赋值。
使用方法1能理解,直接赋值给用reactive包裹的对象也不能这么做。

方法2为什么不行?
只有push或者根据索引遍历赋值才可以保留reactive数组的响应性?
如何方便的将整个数组拼接到响应式数据上?

提供几种办法

const state = reactive({
  arr: []
});

state.arr = [1, 2, 3]
JavaScript
const state = ref([])

state.value = [1, 2, 3]
JavaScript
const arr = reactive([])

arr.push(...[1, 2, 3])
JavaScript

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

打赏: , - (付款时请注明赞赏)

标签: Vue, reactive


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK