How to create a simple application using vue js that stores your daily expenses in a dyanamic form and calculates the total sum that has following fields :
- Name
- Amount
- Date
JS fiddle : https://jsfiddle.net/gitamgadtaula/cbzfj9vn/6/
SOURCE CODE :
<!DOCTYPE html>
<html>
<head>
<title>Vue js - Dynamic calculation form</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container" style="width: 50%;">
<h1>Daily Expense log</h1>
<div
class="card mb-3"
style="background-color: #212529; color: white;"
v-for="(item,i) in expenses"
v-if="i==expenses.length-1"
>
<!-- v-if i==expenses.length-1 because we want to display on the current new form and not previous forms
, remove it if you want to display all other forms -->
<div class="card-body">
<!-- <span class="float-right" style="cursor:pointer" @click="deleteExpenseForm(index)">X</span>
disabled deleting the current form, uncomment to enable -->
<div class="expense-form">
<p>
Name of item:
<input
type="text"
class="form-control mb-2"
placeholder="Please Enter Item name"
v-model="item.name"
/>
</p>
<p>
Amount:<input
type="num"
class="form-control mb-2"
placeholder="in NRS"
v-model="item.amount"
/>
</p>
<p>
Date:<input
type="date"
class="form-control mb-2"
placeholder="yyyy-mm-dd"
v-model="item.date"
/>
</p>
</div>
</div>
</div>
<button
type="submit"
class="btn btn-success"
@click="addNewExpenses();totalSum()"
>
Add expense
</button>
<hr />
<table class="table table-striped table-dark">
<tr>
<th>Id</th>
<th>Name</th>
<th>Amount</th>
<th>Date</th>
<th>Action</th>
</tr>
<tr v-for="(item,index) in expenses">
<td>{{index}}</td>
<td>{{item.name}}</td>
<td>{{item.amount}}</td>
<td>{{item.date}}</td>
<td>
<button
class="btn btn-danger btn-sm"
@click="deleteExpenseForm(index,item.amount)"
>
Delete
</button>
</td>
</tr>
<tfoot>
<tr>
<th colspan="2">Total :</th>
<td colspan="3" style="text-align: right;"><b>{{sum}}</b></td>
</tr>
</tfoot>
</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: ".container",
data() {
return {
expenses: [],
sum: 0,
};
},
methods: {
addNewExpenses() {
this.expenses.push({ name: null, amount: 0, date: null });
},
totalSum() {
console.log(this.sum);
var sum = 0;
for (var i = 0; i < this.expenses.length; i++) {
sum = parseInt(sum);
this.expenses[i].amount = parseInt(this.expenses[i].amount);
sum += this.expenses[i].amount;
this.sum = sum;
}
},
deleteExpenseForm(index, amount) {
this.expenses.splice(index, 1);
this.sum -= amount;
},
},
created() {
this.addNewExpenses();
},
});
</script>
<style>
table {
border-spacing: 1px;
width: 60%;
}
th,
td {
padding: 4px;
border: 1px solid black;
}
</style>
</body>
</html>
Comments
Post a Comment