Categories
Vue 3 Projects

Create a Counter App with Vue 3 and JavaScript

Spread the love

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a counter with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create counter

and select all the default options to create the project.

Create the Counter

We can create the counter by writing:

<template>
  <div>
    <button @click="count++">increment</button>
    <button @click="count--">decrement</button>
    <p>{{ count }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return { count: 0 };
  },
};
</script>

We have the increment button that increments the count reactive property by 1 when we click on it.

And we have the decrement button that decrements the count reactive property by 1 when we click on it.

In the component object, we have the data method that returns an object with count set to 0 as its initial value.

This defines the count reactive property so we can use it in our template.

We can also access it as this.count in the component object.

Also, we can write:

<template>
  <div>
    <button @click="increment">increment</button>
    <button @click="decrement">decrement</button>
    <p>{{ count }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return { count: 0 };
  },
  methods: {
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
  },
};
</script>

to move count++ to increment and count-- to decrement .

We access count as a property of this in the component to access the reactive property.

Conclusion

We can create a counter app easily with Vue 3.

Leave a Reply

Your email address will not be published. Required fields are marked *