Unlock the Power of Event Emitters in Vue.js

Getting Started with Vue.js and Event Emitters

As a developer, you know how crucial it is to pass data between components in your Vue.js application. In this article, we’ll explore how to harness the power of event emitters to update parent components from child components.

Prerequisites

Before we dive in, make sure you have the following installed:

  • Node.js version 10.x or higher (check with node -v)
  • A code editor like VS Code
  • Vue’s latest version installed globally on your machine
  • Vue CLI 3.0 installed on your machine (install with npm install -g @vue/cli)

Passing Data Through Components

In Vue.js, props allow you to pass data from parent components to child components. But what if you need to update the parent component from the child component? That’s where event emitters come in.

Demo: Emitting Events from Child to Parent

Let’s create a demo project to illustrate how to emit events from a child component to update the parent component. We’ll use the Composition API to demonstrate this process.

Step 1: Setting the Emitter

In our child component, we’ll create an emitter that will emit an event when the input value changes. We’ll use the @keyup event to trigger our inputChange function, which will emit the input value in real-time.

<template>
  <input @keyup="inputChange" />
</template>

<script>
export default {
  setup() {
    const inputChange = (event) => {
      // Emit the event with the input value
      emitter.emit('inputChanged', event.target.value);
    };
    return { inputChange };
  },
};
</script>

Step 2: Listening to the Emitted Event

In our parent component, we’ll listen to the emitted event and respond accordingly. We’ll add @newValue="changeTitle" to tell the component to listen to changes on the child and trigger our changeTitle function with the new data.

<template>
  <child-component @newValue="changeTitle"></child-component>
  <p>{{ title }}</p>
</template>

<script>
export default {
  setup() {
    const title = ref('');
    const changeTitle = (newTitle) => {
      title.value = newTitle;
    };
    return { title, changeTitle };
  },
};
</script>

Step 3: Updating the Data Value

Finally, we’ll update the data value in the parent component using the emitted event. We’ll declare title using ref and assign the new child input data to title as the user types.

The result is a real-time update of the parent component as the user types in the child component, demonstrating the power of event emitters in Vue.js.

Leave a Reply