0
0
Vueframework~15 mins

v-on directive for events in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the v-on Directive for Events in Vue
📖 Scenario: You are building a simple interactive webpage where users can click a button to increase a counter. This is a common feature on many websites to track clicks or likes.
🎯 Goal: Build a Vue component that shows a button and a number. When the button is clicked, the number increases by one using the v-on directive to handle the click event.
📋 What You'll Learn
Create a Vue component with a data property called count initialized to 0.
Add a button element in the template with a v-on:click directive to call a method.
Create a method called increment that increases count by 1.
Display the current count value in the template.
💡 Why This Matters
🌍 Real World
Buttons that respond to clicks are everywhere on websites, from liking posts to submitting forms. Learning to handle click events is essential for interactive web pages.
💼 Career
Front-end developers use event handling daily to create dynamic user interfaces that respond to user actions smoothly and accessibly.
Progress0 / 4 steps
1
Set up the initial data property
Create a Vue component with a data function that returns an object containing a property called count set to 0.
Vue
Need a hint?

Use ref from Vue to create a reactive variable count initialized to 0.

2
Add the button with v-on:click directive
In the <template>, add a <button> element with a v-on:click directive that calls a method named increment. Inside the button, write the text Click me.
Vue
Need a hint?

Use v-on:click="increment" on the button to listen for clicks.

3
Create the increment method
In the <script setup> section, define a function called increment that increases the value of count by 1 using count.value++.
Vue
Need a hint?

Define a function named increment that adds 1 to count.value.

4
Display the count value
Inside the <div> in the template, below the button, add a <p> element that shows the current value of count using mustache syntax {{ count }}.
Vue
Need a hint?

Use {{ count }} inside a paragraph to show the current count.