We are going to create a really simple VueJS application to showcase a button click event handling in VueJS.
In the application, there will be two methods and one variable string message. The idea of this application is when a user clicks a button. A message will be displayed to indicate that the user has already clicked the button. Another button will have the purpose of clear the displayed message.
Please see the full HTML code below.
<!doctype html>
<html>
<head>
<title>bytutorial.com Demo - Event Handling Click Button</title>
</head>
<body>
<div id="app">
<p>Click the following button to show a message</p>
<p><input type="button" value="Click Me" v-on:click="clickButton()"/> <input type="button" value="Clear Message" v-on:click="clearMessage()"/></p>
<p>
{{clickMessage}}
</p>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
clickMessage: ''
},
methods: {
clickButton: function(){
this.clickMessage = "You have clicked the button.";
},
clearMessage: function(){
this.clickMessage = "";
}
}
});
</script>
</html>
If you see the above code, we declare the function click methods inside the method's block. You can have multiple methods defined in the block. Just remember to separate each individual method with a comma symbol.
In the VueJS data section. We set the value of the 'clickMessage' to an empty string. In the 'clickButton' method, we set a fixed value into 'clickMessage' string which just indicates that this method has been called and we display the message to the user. The last method which is the 'clearMessage' will perform a clear on the 'clickMessage' variable string.
Demo
To see the live demo, you can click the following link.
See Vue Button Click Event in action.
Download
To download the demo file. Please click the following URL link.