gpt4 book ai didi

javascript - 当值为零时如何阻止计数变为负数?

转载 作者:行者123 更新时间:2023-12-02 17:57:52 30 4
gpt4 key购买 nike

我正在尝试创建一个“添加到卡片”按钮,但我陷入了负计数,基本上,当我们单击“删除零值项目”时,它会变为负数(-1),因为我刚刚开始学习 vuejs 和这对我来说是全新的,因此我们将不胜感激!

<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>

最佳答案

在减法之前检查 count 是否大于 0:(如评论所述,如果您想在计数为0时禁用(或隐藏)递减按钮,您可以绑定(bind)禁用或使用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>

关于javascript - 当值为零时如何阻止计数变为负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75218530/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com