Saturday 6 May 2023

Vue: dynamically remove component: the last component is removed instead of the first, wrong component removed

Code fiddlie: https://codesandbox.io/s/thirsty-austin-ty6f7i?file=/src/App.vue

I have a simple page that allows user to change 3 inputs and add 3 images:

App.vue:

<template>
  <div>
    <div v-for="(line, i) in this.lines" class="line-wrapper" v-bind:key="i">
      <AddImageComponent
        class="add-image"
        matchType="image.*"
        selectButtonText="SELECT OR DROP AN IMAGE"
      />

      <input type="text" v-model="this.lines[i].text" />

      <div class="delete-button" v-on:click.stop="this.lines.splice(i, 1)">
        Delete
      </div>
    </div>
  </div>
</template>

<script>
import AddImageComponent from "./AddImageComponent.vue";
export default {
  name: "App",
  components: {
    AddImageComponent: AddImageComponent,
  },

  data() {
    return {
      lines: [{ text: "A" }, { text: "B" }, { text: "C" }],
    };
  },
};
</script>

<style>
#app {
  background-color: darkcyan;
  height: 100vh;
}

.add-image {
  background-color: lime !important;
  height: 50%;
}

.line-wrapper {
  background-color: purple;
  border: 2px solid black;
  margin-top: 2em;
}

.delete-button {
  background-color: red;
  padding: 5px;
  max-width: 50%;
  border-radius: 10px;
  border: 2px solid red;
}

.delete-button:hover {
  cursor: pointer;
  background-color: transparent;
  border: 2px solid red;
  color: white;
}

input {
  margin: 10px;
  background-color: yellow;
  padding: 5px;
  border-radius: 10px;
  border: none;
}
</style>

The first page I see is this:

enter image description here

When I add the images:

enter image description here

When I click the first (topmost) Delete red button:

enter image description here

So what happens, is that while the texts of the remaining elements are B, and C, (text A was deleted), the pictures are birds and the snake, instead of snake and dog (the last AddImageComponent was removed, instead of the first).

I'm not sure as to what is the best practice way of solving this.



from Vue: dynamically remove component: the last component is removed instead of the first, wrong component removed

No comments:

Post a Comment