I have developed a component that has the ability to contain multiple Value
components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value
components, I provide input fields for name and description. An input event is emitted so that the parent component can store all values from the different components. Clicking on the remove button next to a value triggers a method in the parent component to remove it from the list of values. While the correct value gets removed from the updated list, the issue arises when it removes the last component instead of the intended one. The data in the list seems accurate but the created components do not reflect this properly, even retaining old values. I am having trouble pinpointing the mistake in my code.
ParentComponent
<div v-for="(component, index) in components" v-bind:key="index">
<Value
class="value"
:valueIndex="index"
v-model="components[index]"
:id="'value_' + index"
:isFirst="index === 0"
></Value>
</div>
export default {
name: "Values",
components: {
Value
},
data() {
return {
components: [{
name: "",
description: ""
}],
componentsCount: 1
}
},
methods: {
addValue() {
this.components.push({
name: "",
description: ""
});
},
removeValue(valueIndex) {
console.log(valueIndex);
console.log(this.components[valueIndex]);
this.components.splice(valueIndex, 1);
}
}
ValueComponent
<b-col md="4" sm="12">
<input
type="text"
class="value-input"
v-model="buffer.name"
:name="'description_' + (this.valueIndex + 1)"
:placeholder="'Description ' + (this.valueIndex + 1)"
@input="$emit('input', buffer)"
>
</b-col>
<b-col v-if="isFirst" md="8" sm="12">
<input
type="text"
class="value-input"
v-model="buffer.description"
:name="'description_' + (this.valueIndex + 1)"
:placeholder="'Description ' + (this.valueIndex + 1)"
@input="$emit('input', buffer)"
>
</b-col>
<b-col v-else md="8" sm="10">
<b-row>
<b-col sm="10">
<input
type="text"
class="value-input"
v-model="buffer.description"
:name="'description_' + (this.valueIndex + 1)"
:placeholder="'Description ' + (this.valueIndex + 1)"
@input="$emit('input', buffer)"
>
</b-col>
<b-col sm="2">
<button class="garbage-button" @click="removeValue()">
<img src="../../assets/bin.svg">
</button>
</b-col>
</b-row>
</b-col>
export default {
name: "Value",
props: {
valueIndex: {
type: Number,
required: true
},
isFirst: {
type: Boolean,
required: true
}
},
data() {
return {
buffer: Object.assign({}, this.value)
}
},
methods: {
removeValue() {
this.$parent.removeValue(this.valueIndex);
}
}
}
}
If more code is needed or if there are any clarifications required, please let me know.