[Vuejs]-How to block minus value using v-on:click at Vuejs

4๐Ÿ‘

โœ…

I want to stop when the counter is 0, even though it is clicked.

Just adding a conditional checking before proceeding. Adding this line:
if (this.count === 0) return. Below is a working demo:

new Vue({
  el: "#app",
  data: {
    count: 0
  },
  methods: {
    increment () {
      this.count += 1
    },
    decrement () {
      if (this.count === 0) return
      this.count -= 1
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h2>{{ count }}</h2>
  <button @click="increment">+</button>
  <button @click="decrement">-</button>
</div>

2๐Ÿ‘

There are many ways to do this. You can use the disabled attribute in your negative button when the value is becoming less than or equal to 0. See the following code.

<button
  v-on:click="counter.document -= 1"
  :disabled="counter.document <= 0"
>

0๐Ÿ‘

i think you have a lot of ways to achieving that one of them is this

<button v-on:click=" if(counter.document>0){counter.document -= 1}">-</button>

0๐Ÿ‘

You should avoid complex operation in Template Instead use methods property

new Vue({
  el: "#app",
  data(){
  	return {
    	value: 0
    }
  },
  methods: {
  	subtract() {
    	if(this.value) {
      	this.value -= 1
      }
    }
  }
})
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h2>Todos:</h2>
  <p> {{ value  }}</p>
  <button @click="value+=1">Add 1</button>
  <button @click="subtract" :disabled="!value ? 'true': undefined">Subtract 1</button>
</div>

Leave a comment