My project involves creating a shopping cart application using Vue.js:
var app = new Vue({
el: "#app",
data: {
items: [
{ id: 1, name: "Item 00", spec: "spec 00", price: 400, quantity: 1, unit: "unit 00" },
{ id: 2, name: "Item 01", spec: "spec 01", price: 416, quantity: 1, unit: "unit 01" },
]
},
methods: {
isEmpty: function () {
return this.items.length > 0;
},
handleReduce: function (index) {
if (this.items[index].quantity === 1) {
return;
}
this.items[index].quantity--;
},
handleAdd: function (index) {
this.items[index].quantity++;
},
handleRemove: function (index) {
this.items.splice(index, 1);
},
isDisabled: function (index) {
return this.items[index].quantity === 1;
}
},
computed: {
total: function () {
var total = 0;
for (var i = 0; i < this.items.length; i++) {
total += this.items[i].quantity * this.items[i].price;
}
return total;
},
disabled: function (value) {
return this.items.length < 1;
}
},
filters: {
numberFormat: function (value) {
return value.toString().replace(/\B(?=(\d{3})+$)/g, ',');
}
}
});
This is how I have structured the HTML:
<template v-if="isEmpty()">
<tr v-for="(item, index) in items">
<td>{{ index+1 }}.</td>
<td>{{ item.name }}</td>
<td>{{ item.spec }}</td>
<td class="text-right">{{ item.price | numberFormat }}</td>
<td>
<button class="btn btn-sm btn-secondary" @click="handleReduce(index)" :disabled="isDisabled(index)">-</button>
{{ item.quantity }}
<button class="btn btn-sm btn-secondary" @click="handleAdd(index)">+</button>
</td>
<td>{{ item.unit }}</td>
<td class="text-right">{{ (item.quantity * item.price) | numberFormat }}</td>
<td class="text-right"><button class="btn btn-sm btn-danger" @click="handleRemove(index)">Remove</button></td>
</tr>
</template>
<template v-else>ereNo Items h</template>
<h5 class="text-right mt-5">Total:{{ total | numberFormat }}</h5>
<button class="btn btn-primary" :disabled="disabled">Confirm</button>
I am facing an issue with disabling the "Confirm Button" when the items array is empty. Despite binding the disabled
attribute to the button, it does not work as expected. How can I properly disable the button? Any assistance would be greatly appreciated. Thank you.