使用vuejs3和composition,我异步地从api中获取数据。
const accounts = ref([])
const credits = ref([])
const debits = ref([])
const summary = ref([])
const getaccounts = async () => {
try {
// getData is a preformatted axios function
const response = await getData.get(`/myurl/${route.params.month}/${route.params.year}`)
accounts.value = [...response.data.accounts]
debits.value = [...response.data.accounts].filter(obj => {
return obj.amount < 0
})
summary.value = [...debits.value] // DOESN'T WORK
setSummary(summary.value) // THEREFORE ALSO DOESN'T WORK
credits.value = [...response.data.comptes].filter(obj => {
return obj.amount > 0
})
} catch (error) {
console.log(error)
}
}debits.value是和数组有55个对象,如下所示:
const data = [
{ id: 12, amount : 45, category: "alim" },
{ id: 15, amount : 32, category: "misc" },
{ id: 11, amount : 145, category: "bla" },
{ id: 20, amount : 40, category: "misc" },
{ id: 22, amount : 12, category: "alim" },
{ id: 33, amount : 5, category: "bla" }
]我希望在一个新的对象数组中对每个类别的总金额进行分组。代码在普通的javascript中工作,这就是setSummary函数的样子:
const setSummary = (debs) => {
let arr = debs.reduce((acc, item) => {
let existItem = acc.find(({categorie}) => item.categorie === categorie);
if(existItem) {
existItem.amount += item.amount;
} else {
acc.push(item);
}
return acc;
}, [])
resume.value = arr
}我在summary.value上所做的任何操作都会影响debits.value。我知道Vue反应性是基于Proxy文档的,但我不知道如何克隆或解构对象,使对克隆对象的操作不会影响“父”。
发布于 2022-06-01 23:20:59
你需要深入克隆对象数组。数组元素是引用值。因此,如果您修改summary.value中的元素,它将影响debits.value中的元素。
而不是
summary.value = [...debits.value]试一试
summary.value = JSON.parse(JSON.stringify(debits.value))或者,使用房客
import { cloneDeep } from "lodash"
.....
summary.value = cloneDeep(debits.value)https://stackoverflow.com/questions/72467619
复制相似问题