Search code examples
vue.jsvuexnuxt.js

Vue how to pass child and parent component data to method


I make form with v-for syntax. I successfully get percent data from child component when I write only method name.

Parent component

<div v-for="(item, idx) in recipients"
     :key="idx">
  <range-input @sendValue="getPercentFromChild">
  </range-input>
</div>

...

getPercentFromChild(percent) {
    console.log(percent); // 50
  },

Child component

<div>
  <input type="range"
         value="0"
         @change="sendValue">
</div>

...

export default {
  ...
  methods: {
    sendValue() {
      this.$emit('sendValue', 50);
    },
  }
}

Then, How can I pass child data(percent) and parent data(indx) to methods?

Like this, Parent component

<div v-for="(item, idx) in recipients"
     :key="idx">
  <range-input :currentPercent="0"
               @sendValue="getPercentFromChild(idx, percent)">
  </range-input>
</div>

...

getPercentFromChild(idx, percent) {
   console.log(idx, percent); // 0, undefined
},

Solution

  • you can catch the emitted value with $event parameter, while calling the callback for sendValue event.

    Parent Componet:

    <div v-for="(item, idx) in recipients"
         :key="idx">
      <range-input :currentPercent="0"
                   @sendValue="getPercentFromChild(idx, $event)">
      </range-input>
    </div>
    
    ...
    
    getPercentFromChild(idx, percent) {
       console.log(idx, percent); // 0, 50
    },
    

    here is a demo fiddle