I'm working with BootstrapVue
.
I have a method in my parent.vue
where I pass a value (this.propsIndex
) to my child.vue
.
Now I want to use this value
each time it will be clicked in a method of my child.vue - but how can I trigger my function and make it working?
Thank You very much!
If it's possible I want to avoid using watch
my parent.vue
<template>
<div v-for="(id, index) in inputs" :key="index">
<b-button @click="deleteViaIndex(index)">Delete</b-button>
<child :indexProps="indexProps" />
</div>
<div>
<b-button @click="addInput()">Add Input</b-button>
</div>
</template>
<script>
methods: {
deleteViaIndex(index) {
this.propsIndex= index;
},
addInput() {
this.inputs.push({})
},
},
data() {
return {
inputs: [{}],
propsIndex: '',
}
}
</script>
my child.vue (script)
props: ["propsIndex"],
methods: {
deleteViaParentIndex() {
//HERE I WANT TO USE IT EVERY TIME IT WILL BE CLICKED IN MY PARENT.VUE
//BUT FOR NOW IT'S NOT DOING ANYTHING WHEN I CONSOLE.LOG(this.propsIndex)
}
}
CodePudding user response:
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://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" />
CodePudding user response:
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.each(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.each(child => child.deleteViaParentIndex(index));
}
in child.vue
:
deleteViaParentIndex(index) {
// operations using index
}