Skip to main content

Counter with Increment and Decrement Buttons using VueJS

Submitted by admin on Mon, 06/06/2022 - 21:55
vue-increment-decrement-counter

In this VueJS tutorial we will create a counter with increment and decrement buttons. The value of counter will increase when the user clicks on increment button and value of counter will decrease when the user clicks decrement button.

HTML Part

In below code, I have created a counter and three buttons.
The increment button on click calls a vue function named increase. And decrement button calls a vue function decrease. And reset button calls a vue function reset and this will reset the value of counter back to zero.


<div id="vue-counter">
  <h3>Counter: {{ counter }}</h3>
  <button type="button" v-on:click="increase">Increase By 1</button> <button type="button" v-on:click="decrease">Decrease By 1</button> <button type="button" v-on:click="reset">Reset Counter</button>
</div>

VueJS Code

First we will set the value of counter to zero. We have created three function: increase, decrease, reset.

The function increase will increase the value of counter by one. And function decrease will decrease the value of counter by one. And function reset will reset the value of counter back to zero.


var vueApp = new Vue({
  el: "#vue-counter",
  data: {
    counter: 0,
  },
  methods: {
    increase: function() {
      this.counter++;
    },
    decrease:  function() {
      this.counter--;
    },
    reset: function() {
      this.counter = 0;
    }
  },
})

Demo

Demo - VueJS Counter with Increment and Decrement Buttons

Category

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.