由于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>
效果图: