[Vuejs]-Trigger function in child.vue after clicking button in parent.vue

0👍

Looks like a naming mismatch. In a child component, you have a prop propsIndex, yet in a parent template you are passing indexProps.

When passing props, you have to remember, that prop name is always in the first part, and the value you are passing should go next. https://v2.vuejs.org/v2/guide/components-props.html#Passing-Static-or-Dynamic-Props

Furthermore, since HTML attribute names are case-insensitive, you should pass a prop this way:

<child :props-index="indexProps" />

0👍

Aside from the naming mismatch mentioned by Marcin, you can access a child component from a parent component using a ref in the template:

<child ref="childrenComponents" :props-index="propsIndex" />

Since you have multiple of the child components inside a v-for, this makes the childrenComponents in $refs an array of components. To call deleteViaParentIndex on all of them, you need to iterate through them:

deleteViaIndex(index) {
    this.propsIndex = index;
    this.$refs.childrenComponents.forEach(child => child.deleteViaParentIndex());
}

There’s one more optimization you can make.

Since you’re using propsIndex only to pass an index that the child component uses, and you already have the index as a param in deleteViaIndex, you can simply pass that to the child as a param during the deleteViaParentIndex function call, thus removing the need for the propsIndex data altogether:

in parent.vue:

deleteViaIndex(index) {
    this.$refs.childrenComponents.forEach(child => child.deleteViaParentIndex(index));
}

in child.vue:

deleteViaParentIndex(index) {
    // operations using index
}

Leave a comment