Build a Vue Counter

In this article we'll build a counter with Vue. This is a simple enough example but it is a clean and straight to the point one. We can easily see how the flow of Vue applications works:

  • Define variables in our data
  • Show those variables in our template with interpolation ({{ }}) or directives
  • Listen for events
  • Update the data
  • The template updates itself (reactive!)

We will first create our HTML:

html
<div id="app">

    <!-- show the count here -->
    <h2>{{ count }}</h2>

</div>

We'll start with a simple Vue instance where we can create that count variable:

javascript
const app = new Vue({
    el: '#app',
    data: {
        count: 0,
    }
});

At this point our application will just be able to show the number 0.

Next up we'll need a button that we can click to increment our button.

html
<div id="app">

    <!-- show the count here -->
    <h2>{{ count }}</h2>
    
    <!-- create the button that will increment the count -->
    <button @click="incrementCounter">Count Up</button>
    
</div>

Now we can see our button exists but it won't be able to do anything since we haven't defined the incrementCounter method just yet. We can see that Vue is waiting for the click event though thanks to that @click syntax.

The last step is to add the incrementCounter method to our methods in the Vue instance.

javascript
const app = new Vue({
    el: '#app',
    data: {
        count: 0,
    },
    methods: {
        incrementCounter: function() {
            this.count += 1;
        }
    }
});

Now our application will be able to update the counter!

Let's compare this simple Vue example to vanilla JavaScript. There's a few steps we have to handle ourselves that Vue was already taking care of:

  • grabbing our DOM elements
  • adding our event listeners
  • updating the DOM with new data
javascript
// create our data variables
let count             = 0;
const countPosition   = document.querySelector('h2.title');
const incrementButton = document.querySelector('.button');

// update the html to show the default number
countPosition.innerText = count;

// listen for the click event and increment our counter
incrementButton.addEventListener('click', incrementCounter);
function incrementCounter(e) {
    e.preventDefault();
    count += 1;
    countPosition.innerText = count;
}

Notice the Vue syntax is far more organized and will scale better if we ever bring in multiple counters.

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)