Description:
In my child component, I am working with an array called expenseButton
that is passed as props. The array contains objects with values which I need to calculate the sum of using the array.reduce()
method.
Issue:
While I can successfully get the sum using standard methods, when I try to convert it into a computed property, I encounter the following error message:
Property or method "test" is not defined on the instance but referenced during render
<script>
export default {
props: {
expenseButton: Array,
},
data() {
return {
chosenExpenseId: null
};
},
computed: {
test() {
return this.expenseButton.reduce((acc, curr) => {
acc += curr.expensesValue;
return acc;
}, 0);
}
}
}
};
</script>
<template>
<div>
<div class="yourBalance">
Your monthly balance
<br />
<span>${{ test }}</span>
</div>
</div>
<template>
Additional Info
The "expensesValue" property in the "expenseButton" array is fetched from a backend database using axios
Parent Component
<template>
<div>
<expense-button :myExpense="myExpense" :expenseButton="expenseButton"></expense-button>
</div>
</template>
<script>
import Expenses from "../components/expenses.vue";
import axios from "axios";
export default {
components: {
"expense-button": Expenses
},
data() {
return {
budgetOwner: "",
myExpense: [],
expenseButton: [],
component: "",
errored: false
};
},
beforeRouteEnter(to, from, next) {
axios
.get("/api/budget", {
headers: { "Content-Type": "application/json" },
withCredentials: true
})
.then(res => {
next(vm => {
if (res.data.budget.length > 0) {
vm.myExpense = res.data.budget;
vm.expenseButton = res.data.budget[0].expenses;
}
});
})
.catch(err => {
next(vm => {
console.log(err.response);
vm.errored = true;
});
});
}
}
</script>
Data Retrieved from Database
"budget":[{"expenses":[
{"expensesKey":"a","expensesValue":1,"subExpenses":"","newValue":""},
{"expensesKey":"b","expensesValue":2,"subExpenses":"","newValue":""},
{"expensesKey":"c","expensesValue":3,"subExpenses":"","newValue":""}
]