The v-on
directive in Vue.js is the correct answer to the above question. This simple yet powerful directive is widely used for attaching event listeners that invoke methods, contributing significantly to Vue's functionality and interactivity.
Vue provides us with the v-on
directive for listening to DOM events and executing some JavaScript when they're triggered.
Below is a basic syntax of v-on
:
<button v-on:click="increaseCounter">Increase</button>
In the example above, 'click' is the event we are listening to, and increaseCounter
is the method that will be invoked when the event occurs.
Here is another more complex example, where the method invoked carries an argument:
<div id="message-event">
<p>{{ message }}</p>
<button v-on:click="reverseMessage">Reverse Message</button>
</div>
new Vue({
el: '#message-event',
data: {
message: 'Hello Vue.js!'
},
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
})
In this example, when the button is clicked, the reverseMessage
method is called and reverses the original message.
Best Practices:
@
for v-on
.
<button @click="increaseCounter">Increase</button>
v-on
expressions easier to read.v-for
, v-model
, and v-bind
is also important.Thus, the v-on
directive in Vue.js is crucial for attaching event listeners that trigger given functions, giving life and interactivity to your web components. Understanding how it works and how to use it effectively will significantly elevate your Vue.js mastery level.