Vue Js Button onclick Event:In Vue.js, the v-on:click directive is used to bind a click event to an element such as a button. This allows you to execute a method when the button is clicked. To use this directive, you need to specify the event to listen for (click) and the method to execute when the event is triggered. For example, <button v-on:click="methodName">Click me!</button> will execute the methodName method when the button is clicked. Alternatively, you can use shorthand notation with @click instead of v-on:click. This is a convenient way to add interactivity to your Vue.js applications.
What is the syntax for adding an onclick event to a button in Vue js?
The Below code is an example of how to create a button with an onclick event in Vue.js using a Vue component.
Here’s a breakdown of the code:
- The HTML code defines a button with the text “click me” and attaches an
@clickdirective to it. This directive tells Vue to listen for a click event on the button and call thehandleClickmethod when it happens. - The Vue.js code creates a new Vue instance using
Vue.createApp(), which creates a root component for your application. In this example, the root component has a single method calledhandleClickthat displays an alert when called. - The
app.mount('#app')line tells Vue to mount the root component to the#appelement in the HTML code, which is the container for the button.
When you click the “click me” button, Vue.js will call the handleClick method, which will display an alert with the text “Button clicked”
Vue Js Button onclick Event Example
<div id="app">
<button @click="handleClick">click me</button>
</div>
<script type="module">
const app = Vue.createApp({
methods: {
handleClick() {
alert('Button clicked');
}
}
})
app.mount('#app')
</script>
Output of Vue Js Button onclick Event



