How to Increment and Decrement Number Using Vue 3 Composition Api

In this tutorial we will create simple vuejs counter app using options api and composition api.


Simple Vue 3 Counter App using (Options Api) Example

Counter.vue

<template>
  <div class="flex items-center justify-center gap-x-4">
    <button
      class="px-4 py-2 text-white bg-blue-600 focus:outline-none"
      @click="increment">
      Increment
    </button>
    {{ number }}
    <button
      class="px-4 py-2 text-white bg-red-600 focus:outline-none"
      @click="decrement">
      Decrement
    </button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      number: 0,
    };
  },
  methods: {
    increment() {
      this.number++;
    },
    decrement() {
      this.number--;
    },
  },
};
</script>


Vue 3 Counter App using (Composition Api) Example

Counter.vue

<template>
  <div class="flex items-center justify-center gap-x-4">
    <button
      class="px-4 py-2 text-white bg-blue-600 focus:outline-none"
      @click="increment">
      Increment
    </button>
    {{ number }}
    <button
      class="px-4 py-2 text-white bg-red-600 focus:outline-none"
      @click="decrement">
      Decrement
    </button>
  </div>
</template>
<script>
import { ref } from 'vue';
export default {
  setup() {
    const number = ref(0);

    function increment() {
      number.value++;
    }
    function decrement() {
      number.value--;
    }
    return { number, increment, decrement };
  },
};
</script>