In Vue.js, the v-on directive is used to listen for DOM events and execute JavaScript code. Similarly, v-on can be used on components to listen for custom events emitted by child components.
How to Use v-on to Listen for Custom Events?
First, you need to use the $emit method in the child component to trigger an event. Then, in the parent component, you can use v-on or its shorthand form @ to listen for this event.
Example:
Suppose we have a child component named ChildComponent that triggers an event named update after certain operations:
vue<!-- ChildComponent.vue --> <template> <button @click="handleClick">Update</button> </template> <script> export default { methods: { handleClick() { // Trigger event this.$emit('update', 'new data'); } } } </script>
In this example, when the button is clicked, the handleClick method is called, and it triggers the update event via $emit, passing the data 'new data'.
Now, we need to listen for this update event in the parent component:
vue<!-- ParentComponent.vue --> <template> <div> <child-component @update="handleUpdate"></child-component> <p>Received data: {{ data }}</p> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { data: '' }; }, methods: { handleUpdate(newData) { this.data = newData; } } } </script>
In the parent component, we use @update="handleUpdate" to listen for the update event triggered by ChildComponent. Once the update event is triggered, the handleUpdate method is executed, receives the data from the child component, and updates the parent component's data.
This is the basic method of using v-on in Vue.js to listen for custom events. With this approach, Vue.js components can communicate with each other in a very flexible manner.