I'm creating a bunch of components dynamically and all of these components are the same ( there is literally no difference between them ) . When I press the enter button a new component gets created and actually i'd like to find a way to delete one of these dynamically generated components. The components that i'm dealing with are input fields that have a button on the right side for the deleting feature. I tried hard to make the delete feature but it actually doesn't work and each time I press the delete button, it literally deletes another component. Here is the app. I'd like to delete the components in a correct way. Each button deletes its related input
Here is the child component
<template>
<div>
<div class="dynamiccomponent" @keyup.enter="addNewInput">
<input type="text">
<button @click="deleteInput()">X</button>
</div>
</div>
</template>
<script>
export default {
methods:{
addNewInput(){
this.$emit('newInput')
},
deleteInput(){
this.$emit('deleteInput')
}
}
}
</script>
<style>
.dynamiccomponent{
display:flex;
margin-top:10px;
}
button{
background-color:red;
}
input[type="text"]{
border:none;
background-color:#ccc;
color:black;
}
</style>
Here is the main component :
<template>
<div class="parent">
<div class="flexbox" v-for="(input,index) in inputs" :key="index">
<DynamicInputs @newInput="addNewInput" @deleteInput=deleteInput(index) />
</div>
</div>
</template>
<script>
import DynamicInputs from './components/DynamicInputs.vue'
export default {
components:{
DynamicInputs,
},
data(){
return{
id : 0,
inputs : [[DynamicInputs,0]],
}
},
methods:{
addNewInput(){
this.id=this.id +1
this.inputs.push([DynamicInputs,this.id])
},
deleteInput(index)
{
console.log(index)
this.inputs = this.inputs.filter(input => input[1] !== index)
return this.inputs
}
}
}
</script>