Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass value from child component to parent method AND index

From this answer, I am able to pass a value from a child component to the parent, and call a method in the parent with the value. However, the child components are rendered dynamically with v-for, and I also want to pass the component index to the method I run, along with the value.

I want to do something like this:

<component v-for="(component, index) in components" :key="index" 
:is="component" :index="index" @title-change="setTitle(value, index)" />

If I just use @title-change="setTitle", the value is correctly passed to the setTitle method, without needing to pass it as a parameter.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want the index to be passed, too. None of these work:

@title-change="setTitle(value, index)"
@title-change="setTitle(index, value)"
@title-change="setTitle(index)"

I’m using Vue 2, if that makes any difference.

>Solution :

You can create object with index and title and pass it to parent:

Vue.component('Child', {
  template: `
    <div class="">
      <input v-model="title" />
      <button @click="titleChange">change</button>
      {{title}}
      {{index}}
    </div>
  `,
  props:['index'],
  data() {
    return {
      title: ''
    }
  },
  methods: {
    titleChange() {
      this.$emit('title-change', {idx: this.index, title: this.title})
    }
  }
})

new Vue({
  el: '#demo',
  data() {
    return {
      components: ['child', 'child', 'child']
    }
  },
  methods: {
    setTitle(val) {
      console.log(val)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <component v-for="(component, index) in components" :key="index" 
:is="component" :index="index" @title-change="setTitle" />
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading