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.
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.
CodePudding user response:
You can create object with index and title and pass it to parent:
Vue.component('Child', {
template: `
<div >
<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>