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

After a push to the router, scrolling is disabled

While working on a Vuejs project, I encountered an issue when trying to change the page of my PWA using this.$router.push();. It seems to work fine everywhere else except when doing it from a modal within a component. The pushed page loads but scrolling is ...

I am experiencing an issue where my application, built using NodeJS, Express, and Javascript, is failing to insert form data into the database despite

I am facing a challenge with my app's MVC design pattern where I am unable to insert form information into the corresponding table in the database. Despite installing the body-parser package via npm, the form is not functioning as expected. Can anyone ...

Tips for deleting multiple objects from an array in angular version 13

I am facing an issue where I am trying to delete multiple objects from an array by selecting the checkbox on a table row. However, I am only able to delete one item at a time. How can I resolve this problem and successfully delete multiple selected objects ...

Leveraging jsonp with nodejs and original ajax

I wanted to understand how jsonp works, so I decided to create a demo using nodejs without jQuery. However, I encountered some issues with my code. Here is what I tried: views/index.jade doctype html html head title Demo of jsonp body #res ...

Using Jquery and the cookie.split method to extract and eliminate a value from a cookie

I am trying to figure out how to remove a specific matching value from a cookie using JavaScript. I have written a script that loops over the cookie and checks for matches, but I can't seem to successfully remove just the matching value. Any tips on a ...

The jQuery .hasClass() function does not work properly with SVG elements

I am working with a group of SVG elements that are assigned the classes node and link. My goal is to determine whether an element contains either the node or link class when hovering over any of the SVG components. However, I am encountering an issue where ...

Skip creating declarations for certain files

src/ user.ts department.ts In the scenario outlined above, where there are two files in the src directory (user.ts and department.ts), is there a way to exclude the generation of declaration files specifically for department.ts when running tsc wi ...

Tips on successfully passing multiple keys and their associated HTML tag attributes in a React application

One of my links, specified with an a-tag, appears in this manner: <a href={ item.htmlReportUrl } target="_blank" rel="noopener noreferrer"> {item.htmlReportText}</a> The values for the href and the linktext are sourced from the following: ro ...

When I open Firefox, all I see is a blank page with only the h2 heading displayed

I am trying to print the text "I can print" on a page, but only the title shows up and the rest of the page is blank. What mistake might I be making? <!DOCTYPE html> <html> <head> <title>Object exercise 4</title> </head& ...

The height of the ReactPlayer dynamically adjusts to accommodate content beyond the boundaries of the page

I have a video on my webpage that I want to take up the entire screen, but currently, users have to scroll a bit to reach the bottom, which is not ideal. This is my JavaScript: <div id="page"> <div id="video-container"> ...

Executing the serverless invoke local command produces no output

Attempting to locally run a node lambda for debugging purposes. Utilizing Serverless and the provided launch configuration in vsCode. { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launc ...

React/Next Component Changes State and Clears it in useEffect

Currently, I am faced with an issue while attempting to fetch data from an API. The problem arises during the rendering process since the useEffect function is being called multiple times. Surprisingly, everything works perfectly fine during the initial pa ...

Is there a way to modify the background color of a button once it has been clicked, specifically using JavaScript?

I am looking to change the background color of a button that I have clicked on in my code. Do I need to use loops and conditions for this task? I attempted to access the first index, but I am unsure how to change the background color of other buttons. l ...

JavaScript form validation: returning focus to textfields

I am currently working on a project where I am using JQuery and JavaScript to create an input form for time values. However, I am facing challenges in getting the JavaScript code to react correctly when incorrect input formats are detected. I have a group ...

Perform bulk updates to various rows and columns based on their individual IDs within a Microsoft SQL Server

After extracting data from the database in Excel format using an SQL join query, I made modifications to some columns in the Excel sheet. Now, I need to update the modified data back into the database using the respective row IDs. However, when I try to it ...

Illustrate an element positioned beneath a child element within a different element

I am in the process of designing an overlay on a Google Map that resembles a real map placed on a table, using 2 pixel lines as creases above the map. This design does not significantly impact interactions with the map; only 6 out of 500 vertical lines are ...

What are the reasons for the success function not being called and what steps can be taken to correct it

Whenever I attempt to submit the post, the data is successfully sent and received by the server, but the success function never gets called. In the network inspector tab of Chrome, the connection shows as stalled with a warning: "connection is not finished ...

What is the process for combining multiple Vue components into a cohesive npm package?

My project manager at work tasked me with creating a single npm package for all the global components in our Vue project. This package should be easily importable and usable by everyone working on the project, similar to how Vuetify is imported from the no ...

Guide to integrating WordPress into a subpage of a Nuxt.js website

I'm currently working on a project in nuxtjs 2, deployed on vercel. Additionally, I have a web server that hosts my WordPress site. Is there a way to integrate a WordPress WooCommerce store into my nuxtjs website? Specifically, I would like to create ...

Issue with Element Not Displaying During Page Load with Quick AJAX Request

I attempted to display a loading gif while making an ajax request that takes a long time to respond, and then hide the loading gif once the response is received. Here is the code snippet : $('.loading-gif').show(); $ajax({url:'',async ...