vue3给数组赋值丢失响应式的解决方法

博客指出Vue3因使用proxy,对象和数组不能直接整个赋值。要保留reactive数组的响应性,需通过push或根据索引遍历赋值,并给出了例子和效果图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于vue3使用proxy,对于对象和数组都不能直接整个赋值。

只有push或者根据索引遍历赋值才可以保留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);
  });
  // 方法4 可以
  // arr.length = 0 // 清空原数组
  arr.push(...res)
}

或者

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

或者

const state = ref([]);
...
state.value= res
...

例子

<template>
    <div class="content">
		...
        <Card title="content组件">
            <button @click.prevent="add">ADD</button>
            <button @click.prevent="pop">POP</button>
            <button @click.prevent="changeList">changeList</button>
            {{ list }}
            <ProInj></ProInj>
        </Card>
    </div>
</template>

<script setup lang="ts">
import { reactive, markRaw, ref, defineAsyncComponent, inject, Ref } from 'vue'
...
let flag = ref(true)

let list = inject<Ref<number[]>>('list',ref(reactive<number[]>([])))
// let list = inject<Ref<number[]>>('list', ref<number[]>([1, 2, 3]))
const add = () => list.push(list!.length + 1)
const pop = () => list.pop()

const changeList = () => {
    flag.value = !flag.value
    if (flag.value) {
        list.length = 0
        list.push(...[9, 5, 4, 1])
    }
    else {
        list.length = 0
        list.push(...[6, 6, 6, 6, 6])
    }
}
...
</script>

<style lang="less" scoped>
...
</style>

效果图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凡小多

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值