in Vuejs Basics

VueJS - Click Counter

In this tutorial we're going to build a simple click counter using VueJS. For this we're going to simply have a button on the page and on the click event of the button we need to add 1 to the data property and automatically display this on the page. First we need to create the HTML for the page.

<div id="app">
    <p><button>Add One More Click</button></p>
    <p>The button has been clicked {{ counter }} times</p>
</div>

As you can see we're using the handlebar syntax to display the counter data property from VueJS. Next we need a click event to the button using the Vue directive of v-on:click. Normally you will need to call a method to handle the functionality of adding 1 to a data property. With VueJS we can do this directly in the attribute by simply adding one to the VueJS data property.

<div id="app">
    <p><button v-on:click="counter += 1">Add One More Click</button></p>
    <p>The button has been clicked {{ counter }} times</p>
</div>

Now we can create the Vue Object with a data property of counter.

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            counter: 0,
        }
    })
</script>

View the demo to see this in action. Demo