Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vue.js, how can I emit multiple value from child to parent while parent's v-on pass another parameter?

Tags:

This is a code example.

Vue.component('button-counter', {   template: '<button v-on:click="emit_event">button</button>',   methods: {     emit_event: function () {       this.$emit('change', 'v1', 'v2', 'v3')  // Here I emit multiple value     }   }, }) 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> 

From the parent component, I want to get parameter pass by change() (in this example, 1234), but also every value emitted by child component. I try to use $event to catch the values child emit, however $event is only set up to the first value child emit (int this example, 'v1')

Is there any way to do that? I know I can emit an array to catch multiple value. But some library just emit multiple value.

This is the codepen for above example. https://codepen.io/anon/pen/MmLEqX?editors=1011

like image 224
user2925565 Avatar asked May 24 '17 04:05

user2925565


People also ask

How do you access a root component from a child instance in Vue?

Conclusion. We can access the root Vue instance with $root , and the parent component with $parent . To access a child component from a parent, we can assign a ref with a name to the child component and then use this. $refs to access it.


1 Answers

Define a handler that accepts the multiple parameters from the event and passes them along to the change method in addition to your 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> 

And change your method to

change: function (args) {   this.args = args   console.log(args) } 
like image 63
Bert Avatar answered Oct 03 '22 14:10

Bert