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

wfveoks0  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(116)

我试图创建一个添加到卡按钮,但我坚持计数去负,基本上当我们点击删除项目的值为零,它去负(-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>
dtcbnfnu

dtcbnfnu1#

在减去之前,只需检查计数是否大于0:

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

相关问题