Home > Back-end >  Vue js- Hide minus button when the value reaches 0 and unhide plus button in
Vue js- Hide minus button when the value reaches 0 and unhide plus button in

Time:10-23

The idea is when the minus button is clicked until 0, I need to hide the minus button and then unhide the plus button to add the value again. What I have tried here I managed to make the minus and plus function. Anyone can help I'm still new in vuejs.

<template>
  <div class="message"># {{ count }}<br>
    <p># {{ count }}</p>
    <button v-on:click.prevent="increment"> </button>
    <button v-on:click.prevent="decrement">-</button>
  </div>
</template>
    
<script>
export default {
  data: ()=> {
    return {
      count: 5
    }
  },
  methods: {
    increment() {
      this.count  ;
    },
    decrement() {
      if(this.count > 0) {
        this.count-- ;
      }
    }
  }
}
</script>

CodePudding user response:

You can use v-show directive based on count value:

new Vue({
  el: '#app',
  data: () => {
    return {
      count: 5
    }
  },
  methods: {
    increment() {
      this.count  ;
    },
    decrement() {
      if (this.count > 0) {
        this.count--;
      }
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
  <div class="message">
    <p># {{ count }}</p>
    <button v-show="count >= 0" v-on:click.prevent="increment"> </button>
    <button v-show="count > 0" v-on:click.prevent="decrement">-</button>
  </div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Try to use v-if

new Vue({
  el: '#demo',
  data: ()=> {
    return {
      count: 5
    }
  },
  methods: {
    increment () {
      this.count  ;
    },
    decrement () {
      if(this.count > 0){
        this.count-- ;
      }
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
      <div class="message"># {{ count }}<br>
        <p># {{ count }}</p>
        <button v-on:click.prevent="increment" > </button>
        <button v-on:click.prevent="decrement" v-if="count">-</button>
    </div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can do this to hide the - when the value is 0:

<button v-if="count > 0" v-on:click.prevent="decrement">-</button>
  • Related