How do I send multiple values from a child to a parent in Vue.js, while also passing another parameter in the parent's v-on event?

Behold, a demonstration of code.

Vue.component('button-counter', {
  template: '<button v-on:click="emit_event">button</button>',
  methods: {
    emit_event: function () {
      this.$emit('change', 'v1', 'v2', 'v3')  // Behold the emission of multiple values
    }
  },
})
new Vue({
  el: '#parent',
  data: {
    args: ""
  },
  methods: {
    change: function (...args) {
      this.args = args
      console.log(args)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.common.js"></script>
<div id="parent">
  {{ args }} <br />
  <button-counter v-on:change="change(1234, $event)"></button-counter>
</div>

The goal is to receive not only the parameter passed by the change() method from the parent component (in this case, 1234), but also all values emitted by the child component. An attempt was made using $event to capture the emitted values from the child, however, it only captures the first value emitted by the child (in this example, 'v1')

Is there a solution for this? While emitting an array works for catching multiple values, some libraries emit values individually.

Here's the codepen link for the example showcased above: https://codepen.io/anon/pen/MmLEqX?editors=1011

Answer №1

Create a function that can handle various parameters from an event and send them to the change method along with a static parameter.

<button-counter v-on:change="(...args)=>this.change(1234,...args)"></button-counter>

Alternatively

<button-counter v-on:change="(...args)=>this.change([1234,...args])"></button-counter>

Update your method to

change: function (args) {
  this.args = args
  console.log(args)
}

Answer №2

To simplify your code, you can utilize destructuring syntax

this.$emit('update', { a:'value1', b:'value2', c: 'value3' })

Then, you can easily access these values by following this example

<custom-component @update="update"></custom-component>

methods: { update({a, b, c}) { .... } }

Answer №3

Here's my approach:

<counter-button v-on:click="update(1, ...args)">

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

Update nbind using `NODE_MODULE_VERSION 70` rather than `NODE_MODULE_VERSION 48`

I am currently working on a project using Electron. The main file where my application is launched is ./src/index.js: const { app, BrowserWindow, ipcMain } = require('electron'); const nbind = require('nbind'); const lib = nbind.init() ...

Issues with styled-components media queries not functioning as expected

While working on my React project with styled components, I have encountered an issue where media queries are not being applied. Interestingly, the snippet below works perfectly when using regular CSS: import styled from 'styled-components'; exp ...

Having trouble accessing object properties fetched via API, receiving the error message "TypeError: Cannot read property '' of undefined" in Next.js with JavaScript

Encountering a unique issue specific to NextJs. Fetching data from an API using a custom hook and receiving an array of objects as the result. Successfully logging the entire result (array of objects). const myMovieGenreObjects = useFetchNavBarCategories( ...

Why does my jQuery map code work in version 2.0 but not in version 3.0?

I've encountered an error with a jQuery map snippet that I'm trying to troubleshoot. It was working fine under jQuery 2, but after upgrading to version 3, it doesn't work anymore and I can't figure out why. Feeling stuck! var menuIte ...

Having trouble retrieving data sent via ajax in PHP

Currently, I am using Ajax to send a variable in my PHP file. Here's the code snippet: getVoteCount: function(){ App.contracts.Election.deployed().then(function(instance) { for(i=0; i<4; i++){ instance.candidates(i).then(functi ...

The react-datepicker component is unable to set the state to the format dd/MM/yy

The date is currently shown in the correct format (31/08/21), but when onChange gets triggered, startDate changes to something like this: Tue Aug 31 2021 21:29:17 GMT+0200 (Central European Summer Time) Is there a way to maintain the display format I wa ...

Not all dynamic content is loaded through Ajax requests on a single domain

I currently have my domain forwarded (cloaked) to The main page (index.html) utilizes Ajax for loading content. All content loads properly at the original host (moppy.co.uk/wtcdi). However, on the forwarded domain (whatthecatdragged.in), some content fai ...

search for a specific value within a nested subfield of an asterisk star field in Firestore

Here is the data I have: { root: { _rEG: { fen: 'value' }, _AS: { fen: 'value' }, _BSSA: { fen: 'value' } } } I would like to query using where('root.*.fen', '==', 'value'). ...

Send a Javascript variable to a Python controller using AJAX

Programming is still new to me and I find myself in unfamiliar territory... I am working on creating an app that relies on button clicks to gather information and provide data analysis based on those interactions. While this functionality works using pure ...

New to React: Arrow Function Example that Might Puzzle You

As a beginner in React/ES6, I came across this code snippet for handling a checkbox within a custom component that contains a material-ui CheckBox. My goal is to expand the custom component by adding more fields, such as a textbox where users can provide a ...

Obtain the numerical value of the vertical position of the mouse (

Currently, I am coding a JavaScript game and my objective is to designate a variable specifically for the Y axis of the mouse. I kindly request that the code be kept as simple and straightforward as possible, avoiding unnecessary complexity. That conclud ...

A guide on accessing objects from an array in Vue.js

Wondering how to choose an object from an array in Vue.js: When the page loads, the selectTitle() function is triggered. I simply want to select a specific object (for example, i=2) from my 'titleList' array. However, at the moment, I am only re ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

Leveraging promises in conjunction with mongoose operations

I'm new to using promises in conjunction with mongoose query functions such as find() and findById(). While everything seems to be functioning correctly, I am unsure if the way I am chaining then is the proper approach. The goal of utilizing promises ...

Lowest value malfunctioning

I have encountered an issue with setting minimum values for 4 things. All 4 things are supposed to have the same minimum value as the first thing, but when moving the slider, everything goes back to normal and works fine. Where could the problem be origina ...

Can the unique identifier for a datalist item be retrieved upon choosing an item from the list?

I am looking for a way to retrieve the key associated with an item in a datalist when it is selected. The code below populates a search box with datalist items where the key is set to u.userID and the display is set to u.name. After selecting an item, I ...

Can a JavaScript callback be transmitted via JSON?

Is there a way to pass a callback function via JSON instead of using a function object? window.onpopstate = function(e) { var state = e.state; switch(state['method']) { case 'updateFields': updateFields(sta ...

Having difficulty importing app.js into other modules within ExpressJS

Having trouble importing app.js into other modules in ExpressJs. It imports successfully, but I can't use the functions defined in the app.js file. The code snippet I am working with is as follows: I have this app.js var app = express(); var express ...

Searching for a method in Vue to monitor values and updates from a distinct component or JavaScript file

I am working with a plain JavaScript file that includes various functions, one of which retrieves a value from either 1. local storage, 2. Vuex, or uses a default value if neither is present. These values can be updated throughout the entire application by ...