Simple Counter Animation in Nuxt3

Simple Counter Animation in Nuxt3

·

2 min read

Let's create a very simple counter animation with Nuxt3 and the Composition API. At the end of this post and with a few lines of code we should have something like this:

Nuxt 3 - Project

First, you need to create a Nuxt project. I also added tailwind to the project which is not necessary. If you want to get tailwind inside your Nuxt project have a look at this Nuxt3 Google Map Component. This will help you to understand you can set up a Nuxt project and it also shows you how to add tailwind to your project!

The component

We only need a couple of lines of code to get a counter. To create a counter animation we just start at 0 and do the counting which is being displayed in the browser.

<script setup>
const counter = ref(0);

setInterval(() => {
    if(counter.value < 100) {
        counter.value++;
    }
}, 10);
</script>
<template>
    <div class="w-full flex flex-col justify-center h-screen">
        <p class="flex justify-center">
            <span class="text-9xl">{{ counter }}</span>
        </p>
    </div>
</template>

That's all the code we need! We are using the Composition API. Then we declare our counter ref which has the value 0.

Incrementing the counter.value is enough to get an animation. However, we need to set an interval. If you don't set the interval you would instantly get 100 to avoid this we set the interval to 10.

To slow down the animation simply increase the time of the interval for example to 50.
If the counter should only count to 50, simply adjust the if-statement.

Use-Case

I think there are not a lot of use cases for this. But if you get a value from a backend things change. You can simply create a counter component that counts to any value a user configures. Maybe you can use this to display the number of downloads of your app or something like this.

Did you find this article valuable?

Support Joschi by becoming a sponsor. Any amount is appreciated!