rewrite the assignment to composition API

This commit is contained in:
Andreas Zweili 2021-09-04 14:11:17 +02:00
parent 0fd64caecc
commit 2a9a6a8907
1 changed files with 31 additions and 24 deletions

View File

@ -3,10 +3,10 @@
<h1>Expense Tracker</h1> <h1>Expense Tracker</h1>
</header> </header>
<section> <section>
<div>Available Funds: {{ availableFunds }}</div> <div>Available Funds: {{ data.availableFunds }}</div>
<div>Total Expenses: {{ currentExpenses }}</div> <div>Total Expenses: {{ data.currentExpenses }}</div>
<hr /> <hr />
<div>Funds left: {{ remainingFunds }}</div> <div>Funds left: {{ data.remainingFunds }}</div>
</section> </section>
<section> <section>
<form @submit.prevent="addExpense"> <form @submit.prevent="addExpense">
@ -20,31 +20,38 @@
</template> </template>
<script> <script>
import { ref, reactive, computed, watch } from 'vue';
export default { export default {
data() { setup() {
return { const data = reactive({
availableFunds: 100, availableFunds: 100,
currentExpenses: 0, currentExpenses: 0,
enteredExpense: 0, enteredExpense: 0
}; });
},
computed: { const enteredExpense = ref(0);
remainingFunds() {
return this.availableFunds - this.currentExpenses; data.remainingFunds = computed(function() {
}, return data.availableFunds - data.currentExpenses;
}, });
methods: {
addExpense() { function addExpense() {
this.currentExpenses += this.enteredExpense; data.currentExpenses += enteredExpense.value;
}, }
},
watch: { watch(data, function(_, newValue) {
remainingFunds(val) { if (newValue.remainingFunds < 0) {
if (val < 0) {
alert('You are broke!'); alert('You are broke!');
} }
}, });
},
return {
data,
addExpense,
enteredExpense
};
}
}; };
</script> </script>
@ -99,4 +106,4 @@ button:active {
background-color: #5819ac; background-color: #5819ac;
border-color: #5819ac; border-color: #5819ac;
} }
</style> </style>