Effortlessly communicate events from a nested component to its parent in Vue 2

In my project, I created a base component called BaseInput.vue which accepts attributes and emits events. To easily bind all attributes, I use the v-bind="$attrs" directive.

// BaseInput.vue
<template>
  <label>
    <input
      v-bind="$attrs"
      @focus="$emit('focus')"
      @blur="$emit('blur')"
    >
  </label>
</template>

<script>
export default {
  inheritAttrs: false,
};
</script>

Next, I have another component called WrapInput.vue that acts as a wrapper for BasicInput by passing attributes and emitting events.

// WrapInput.vue
<template>
  <basic-input
    v-bind="$attrs"
    @focus="$emit('focus')"
    @blur="$emit('blur')"
  />
</template>

<script>
import BasicInput from '@/storybook/pages/BasicInput';

export default {
  components: { BasicInput },
  inheritAttrs: false,
};
</script>

My query is whether there is a more efficient way in Vue to pass multiple events to "proxy" components without having to list them individually. I envision something like this:

// WrapInput.vue
<template>
  <basic-input
    v-bind="$attrs"
    v-bind="$events" // Is there a way to proxy all events in one line?
  />
</template>

<script>
import BasicInput from '@/storybook/pages/BasicInput';

export default {
  components: { BasicInput },
  inheritAttrs: false,
};
</script>

P.S. Although I've heard about EventBus, it doesn't seem to be the best fit for my specific situation.

Answer №1

When working with Vue 2, event listeners could be passed to a component using v-on and $listeners:

// BasicInput.vue
<input v-on="$listeners">

Check out this Vue 2 demo

However, in Vue 3, $listeners is no longer available. Instead, event listeners are now part of $attrs, so simply use v-bind="$attrs".

Here's a Vue 3 demo

Answer №2

Efficient Communication Method using Event Bus in Vue.js Event bus in Vue.js enables seamless communication between any two components regardless of their relationship. This method is ideal for situations where manual event handling on a component instance is required.

To transmit data from one component to another, simply use

this.$root.$emit(’name-of-emitter’, args1, args2, ...)
, and then capture it using
this.$root.$on(’name-of-emitter’, args1, args2, ...)
in the receiving component.

For more insights, refer to the original article: https://dev.to/sanchithasr/how-to-communicate-between-components-in-vue-js-kjc

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

HTML5 Video Frozen in Place on Screen's Edge

I am encountering a problem specifically on Webkit, particularly in web view on iOS. When I tested it on desktop Chrome, the issue did not appear. Here is the Portrait image and Here is the Landscape image The video seems to be fixed in one position rega ...

Creating unique page styles using global styles in Next.js

I am facing a dilemma in my NextJS app. On the /home page, I need to hide the x and y overflow, while on the /books page, I want the user to be able to scroll freely. The issue is that Next only allows for one global stylesheet and using global CSS selec ...

Every single checked value in the checkbox variable

Encountered a small hiccup. Let me explain. In my form, there are 8 checkboxes. The goal is to loop through and capture the value of each checked checkbox using a variable. However, I'm always getting the same value from the first checkbox. Here&apo ...

Transforming HTML code into a structured object

The provided code snippet includes HTML markup that needs to be transformed into a specific format. <html> <head> <title>Hello!</title> </head> <body> <div class=”div1”> <h1>This is a ...

Loop through the JSON data to obtain distinct values for certain indices

My PHP script retrieves data with the following query: SELECT objective,signal_type,signal_name FROM signals WHERE channel="Email" This is how the data is returned: [ { "objective": "Awareness", "signal_type": "Efficiency", " ...

Tips for ensuring session token verification remains intact upon reloading

I am currently in the process of developing a website using the Next.js framework and I am seeking advice on how to prevent the reload effect that occurs when transitioning from the login page back to the main page for just a fraction of a second. Below i ...

AngularJS Datepicker - calendar dropdown does not update when the model changes

I've been facing a challenge with the AngularJs datepicker in my project for some time now. Within my application, users have the option to either manually select a date using the calendar or click on "This Month" to automatically set the date to the ...

What is the best way to retrieve the initial cell from a row that the user is currently hovering over?

Is there a way to extract the first cell from a row when a user hovers over it and then clicks a specific key combination? (considering using jQuery) I have a table set up similarly where placing the mouse over a tr and pressing ctrl+c will copy the ID t ...

Interactive table with Draggable feature supported by Bootstrap Vue

After tirelessly searching for a solution to drag and drop rows on a Bootstrap Vue table, I finally stumbled upon a functional version here: Codepen I attempted to integrate this code into my own table: Template: <b-table v-sortable="sortableOptions ...

v-for loop doesn't iterate over imported array

I am facing an issue with importing data from a file named clients.js into another file called clients.vue. My goal is to display the imported data in a table within the clients.vue file, but I am unable to access it after importing. Interestingly, if I c ...

Eliminate the standard blue border that appears when control-clicking on table elements

I've encountered this question before, but unfortunately none of the solutions provided have worked for me. Some things I've attempted are: Using event.preventDefault() - did not produce the desired result. Removing user-select from CS ...

Enhancing TypeScript builtin objects in Netbeans using a custom plugin

While in the process of converting JavaScript code to TypeScript, I encountered a challenge with extending built-in objects using Object.defineProperty, such as String.prototype. Object.defineProperty(String.prototype, 'testFunc', { value: funct ...

How to Remove Carousel Arrows in Bootstrap 5

Any suggestions on how to remove the previous and next arrows in a Bootstrap carousel, particularly on the first and last slide? I'm struggling to find a solution for Bootstrap 5 as most solutions available are for older versions. Your help would be g ...

Updating attribute values in a dynamic JSON file with Node.js: A step-by-step guide

My task involves checking if the key in input.json file matches any key in the server.json file, and then updating the value in the server.json file. The challenge lies in the fact that the server.json file is dynamic with an unpredictable structure contai ...

Difficulty: Issue with displaying Backbone collection using Mustache template

I'm new to backbone js and Mustache. I want to load a backbone collection on page load from rails json object to avoid making an extra call. However, I'm facing issues when trying to render the backbone collection using a mustache template. Here ...

JS editing an array in a datatable

I have created an HTML page where users can enter data, which is then uploaded to a SQL server. I have been studying DataTables to load an array into a table and tried editing it, but still haven't had success. Can anyone offer assistance? var array ...

Experiencing trouble with setting values in JavaScript?

I have my code set up to display numbers 170 and 122 using Javascript, but I'm not seeing the expected output. <!DOCTYPE html> <html> <body> <button onclick="UidToPost()">Get It</button> <script> ...

Are non-local variables in Node.js considered safe to use?

Would it be secure to implement this code in Node.js/Express.js? // using Object.create(null) to avoid key collisions // refer http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ var theHash = Object.create(null); exports.store = function (req, ...

Develop interactive applications with React Native by generating N animated values

Currently, I am in the process of developing a component known as a "Color Palette," which includes a prop called "paletteColors." The "paletteColors" prop is an array with varying lengths that houses color values represented as strings. Within this comp ...

Internet Explorer displaying incorrect formatting for HTML CSS tables

Having an issue with table display on IE 9/10/11. Tested code on different browsers and platforms, everything looks good except when viewed on my HTTP server (lighttpd and python SimpleHTTPServer), the table is showing up incorrectly: var cell = $(&apos ...