Vue3 encounters reactive response invalidation problem record

Brief description of the situation: A reactive empty array is initialized, and then the interface is called to assign the data returned by the interface to the reactive. At this time, it is found that the page data has not been updated. (Scenario: dataList of ele-table)

const dataList = reactive([]);
const load = async () => {
  const res = await 接口函数(); //假设请求接口返回的数据
  // 方法1 失败,直接赋值丢失了响应性
  // dataList = res;
  // 方法2 这样也是失败
  // dataList.concat(res);
};

reason:

Directly assign a new array to dataList, causing the reactive object declared by reactive to be proxied by dataList

Replaced by a new array, because the proxy object needs to be used as a premise when operating the proxy object, so the responsiveness is lost

In vue3, no matter whether it is an object or an array, the entire data cannot be directly assigned, which will cause the reactive definition of reactive to fail.

Just like the address of the object is replaced, it is not the original object

Solution:

方法1:创建一个响应式对象,对象的属性是数组
let datalist = reactive({
  list: [],
})
let arr = [1,2,3]
datalist.list = arr

方法2:使用ref函数(ref可以创建任意数据类型,reactive只能创建对象或者数组)
const datalist = ref([])
datalist.value = [1, 2, 3]

方法3:数组的push
let datalist = reactive([])
let arr = [1, 2, 3]
arr.forEach((item) => { 
 datalist.push(item)
})
 
 
let datalist = reactive([])
let arr = [1, 2, 3]
datalist.push(...arr)

Guess you like

Origin blog.csdn.net/m0_57033755/article/details/129043116