简体   繁体   中英

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

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

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)
}

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}) { .... } }

我会这样做:

<button-counter v-on:change="change(1, ...arguments)">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM