How to emit custom events from child components in Vue.js?

To emit custom events from child components in Vue.js, follow these steps:

  1. First, define an event in the child component that you want to emit. This can be done using a method or a computed property. For example, let's assume you have a button in the child component that you want to emit a 'custom-event' when clicked. You can define the event like this:
methods: { emitCustomEvent() { this.$emit('custom-event'); // Emit the 'custom-event' } }
  1. In the parent component where the child component is used, you can listen for the custom event by adding a listener to the child component. For example:
<template> <div> <child-component @custom-event="handleCustomEvent"></child-component> </div> </template> <script> export default { methods: { handleCustomEvent() { // Custom event handling logic console.log('Custom event emitted from child component'); } } } </script>

In the example above, the @custom-event is the listener for the custom event emitted from the child component. When the event is emitted, the handleCustomEvent method in the parent component is called.

  1. Now, when the button in the child component is clicked, the custom event will be emitted and the corresponding handler in the parent component will be executed.