Reputation: 1402
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
Upvotes: 41
Views: 97138
Reputation: 383
You can use destructuring syntax
this.$emit('change', { x:'v1', y:'v2', z: 'v3' })
And you can access these values like so
<button-counter @change="change"></button-counter>
methods: { change({x, y, z}) { .... } }
Upvotes: 35
Reputation: 101
I would do this:
<button-counter v-on:change="change(1, ...arguments)">
Upvotes: 10
Reputation: 82469
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)
}
Upvotes: 36