Vue.js makes use of v-on
directive to listens to events. Using v-on
we can call a method whenever an event is triggered. For example, to show a message when user clicks on a button.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<title>Vue.Js</title>
</head>
<body>
<div id="app">
<div>Click to generate a random number</div>
<button>Click Here!</button>
</div>
</body>
</html>
In this example, we have a button that generates a random number every time the user clicks the button.
<button>Click Here!</button>
Let’s make use of the v-on
directive to call a method when the button is clicked.
<button v-on:click="getRandomNumber()">Click Here!</button>
Here, we have specified the v-on
directive for the click event(v-on:click
) to call the method getRandomNumber()
which we will define next.
getRandomNumber() {
this.number = Math.round(Math.random() * 1000);
}
The getRandomNumber()
generates a random number and assigns it to the number
property.
In our HTML we can use a <p>
tag to display this number.
<p>{{ number }}</p>
So the entire code should like below:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<title>Vue.Js</title>
</head>
<body>
<div id="app">
<div>Click to generate a random number</div>
<button v-on:click="getRandomNumber()">Click Here!</button>
<p>{{number}}</p>
</div>
</body>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
number: "",
};
},
methods: {
getRandomNumber() {
this.number = Math.round(Math.random() * 1000);
},
},
}).mount("#app");
</script>
</html>
Every time the user clicks the button a random number will get displayed on the screen.
We can also write the above code using the v-on
shorthand @
.
<div id="app">
<div>Click to generate a random number</div>
<button @click="getRandomNumber()">Click Here!</button>
<p>{{number}}</p>
</div>