尝试在 get axios 请求上使用 async/await。我试图将response.data保存到transaction.value,它是一个代理对象,导致无法在其上使用“reduce”函数,因为它在数组上工作。如何保存响应,使其成为数组?
下面是我的App.vue代码:
<template>
<PageHeader />
<div class="container">
<Balance :total="total" />
<IncomeExpense :income="+income" :expense="+expense" />
<TransactionList
:transactions="transactions"
@transactionDeleted="handleTransactionDeleted"
/>
<AddTransaction @transactionSubmitted="handleTransactionSubmitted" />
</div>
</template>
<script setup>
import PageHeader from './components/PageHeader.vue'
import Balance from './components/Balance.vue'
import IncomeExpense from './components/IncomeExpense.vue'
import TransactionList from './components/TransactionList.vue'
import AddTransaction from './components/AddTransaction.vue'
import { useToast } from 'vue-toastification'
import axios from 'axios'
import { ref, computed, onMounted } from 'vue'
const toast = useToast()
const transactions = ref([])
const fetchTransactions = async () => {
try {
const response = await axios.get('/data-api/rest/personaltransactions')
transactions.value = response.data
console.log(transactions.value)
} catch (error) {
console.log(error)
}
}
onMounted(() => {
fetchTransactions()
})
const total = computed(() => {
return transactions.value.reduce((acc, transaction) => { <---- 'reduce' error here
return acc + transaction.transaction_amount
}, 0)
})
</script>
我对 Vue 有点生疏,找不到官方的 Vue 原生方法来做到这一点,但 Vue 主要贡献者 Anthony Fu 致力于 VueUse,这是 Vue 组合实用程序的集合,其中包括 useArrayReduce可以像下面的演示一样使用。
您可以使用它,也可以深入研究源代码来找到自己实现的方法
现场演示
const { createApp, ref, computed } = Vue;
const { useArrayReduce } = VueUse; // <----------------------------------------
const app = createApp({
setup() {
const transactions = Vue.ref([]);
const total = Vue.computed(() => {
return useArrayReduce(transactions, (acc, transaction) => { // <--------
return acc + transaction.transaction_amount;
}, 0);
});
// Just for the demo
(function asyncLoop() {
transactions.value = Array.from({ length: 4 }, () => ({
transaction_amount: Math.floor(Math.random() * 10)
}));
setTimeout(asyncLoop, 1000);
})();
return {
transactions,
total
};
}
})
.mount("#app");
<div id="app">
<p>Transactions: <span>{{transactions.map(t => t.transaction_amount)}}</span></p>
<p>Total: <span>{{total}}</span></p>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/@vueuse/shared"></script>
<script src="https://unpkg.com/@vueuse/core"></script>