Advertisements
I’m trying to create an add to card button but I’m stuck on the count going negative,basically when we click on remove item at value zero its goes negative(-1) since I have just started learning vuejs and this is totally new to me so any help would be apreciated!
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
},
decrement(){
this.count--
}
},
mounted() {
this.increment()
// this. decrement()
}
}
</script>
<template>
<div class="btn-container">
<!-- <button class="button"> count is : {{ count }}</button><br> -->
<button class="button" @click="increment">add to cart</button>
<button class="button" @click="decrement">remove item</button>
</div>
<h1 v-if= count> item added {{count}} </h1>
<h1 v-else-if = count> please add item </h1>
<h1 v-else> no item 😢</h1>
</template>
<style>
.btn-container{
align-items:"center";
justify-content:"center";
display: flex;
padding:5px;
margin:5px;
background-color: red;
}
.button{
padding : 1vw;
margin: 1vw;
background-color: aquamarine;
border-radius: solid 1px;
}
</style>
>Solution :
Just check if count is greater of 0 before substract:
(as commented if you want to disable(or maybe hide) decrement button when count is 0, you can bind disabled or use v-show)
const { reactive, onMounted } = Vue
const app = Vue.createApp({
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
},
decrement(){
this.count > 0 && this.count--
}
},
mounted() {
this.increment()
// this. decrement()
}
})
app.mount('#demo')
.btn-container{
align-items:"center";
justify-content:"center";
display: flex;
padding:5px;
margin:5px;
background-color: red;
}
.button{
padding : 1vw;
margin: 1vw;
background-color: aquamarine;
border-radius: solid 1px;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div class="btn-container">
<!-- <button class="button"> count is : {{ count }}</button><br> -->
<button class="button" @click="increment">add to cart</button>
<button class="button" :disabled="!count" @click="decrement">remove item</button>
</div>
<h1 v-if= count> item added {{count}} </h1>
<h1 v-else-if = count> please add item </h1>
<h1 v-else> no item 😢</h1>
</div>