Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
Delete a specific component while making dynamic rendering (VueJS)

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>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think that your problem is that once you delete an element which is not the last of the list, your indices you set manually are messed up.

if I start with:

const inputs = [
  ["a", 0],
  ["b", 1],
  ["c", 2]
]

and delete the second item I end up with:

const inputs = [
  ["a", 0],
  ["c", 2]
]

The indices I set initially are now not consistent any more.

My advice is to follow completely different approach.

  1. Define a list of inputs. For examlpe inputs = ["a", "b", "c"] will be used to render 3 DynamicInputs. Each DynamicInput gets passed one of those strings.

  2. Communicate changes to a DynamicInput back to the parent. This can be done best through v-model and a computed property based on your prop. In the computed property you define a getter and a setter. In the setter you emit an event back to the parent, so that the value change can be done in the parent component.

  3. delete using splice. With splice you can tell an array where (and how many) elements to remove from the array

This is how the parent component can look like

<template>
  <div class="parent">
    <div class="flexbox" v-for="(inputVal, index) in inputs" :key="index">
      <DynamicInputs
        :input-value="inputVal"
        @change-input="changeInput($event, index)"
        @new-input="addNewInput"
        @delete-input="deleteInput(index)"
      />
    </div>
  </div>
</template>

<script>
import DynamicInputs from "./DynamicInput.vue";
export default {
  components: {
    DynamicInputs,
  },
  data() {
    return {
      inputs: ["a", "b", "c", "d"],
    };
  },
  methods: {
    changeInput(data, index) {
      this.inputs[index] = data;
    },
    addNewInput() {
      this.inputs.push("");
    },
    deleteInput(index) {
      this.inputs.splice(index, 1);
    },
  },
};
</script>

and this how the DynamicInput component

<template>
  <div>
    <div class="dynamiccomponent" @keyup.enter="addNewInput">
      <input v-model="computedInput" type="text" />
      <button @click="deleteInput()">X</button>
    </div>
  </div>
</template>

<script>
export default {
  emit: ["new-input", "delete-input", "change-input"],
  props: ["input-value"],
  methods: {
    addNewInput() {
      this.$emit("new-input");
    },
    deleteInput() {
      this.$emit("delete-input");
    },
  },
  computed: {
    computedInput: {
      get: function () {
        return this.inputValue;
      },
      set: function (newVal) {
        this.$emit("change-input", newVal);
      },
    },
  },
};
</script>

<style>
.dynamiccomponent {
  display: flex;
  margin-top: 10px;
}
button {
  background-color: red;
}
input[type="text"] {
  border: none;
  background-color: #ccc;
  color: black;
}
</style>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda