rfpdl
rfpdl

Reputation: 964

Removing component at index 0 remove all item

I have a component inside a loop, and a remove button per component.

If I remove components at index 1 and above, it is removing fine, but when I remove an item at index 0 (first one), all of the components disappear but the data is still available in the Vue console.

//form.vue
<template>
  <div>
    <div
      v-for="(item, index) in items"
      :key="index"
    >
      <viewer
        :item="item"
        :index="index"
        @removed="remove"
      ></viewer>
    </div>
  </div>
</template>
<script>
import default {
  //truncated
  data() {
    items: ['sample 1', 'sample 2', 'sample 3']
  },
  methods: {
    remove(index) {
      this.items.splice(index,1)
    }
  }
}
</script>
//viewer.vue
<template>
  <div>
    <div>{{ item }}</div>
    <div @click="remove()">Remove</div>
  </div>
</template>
<script>
import default {
//tuncated
  props: {
    item,
    index
  },
  methods: {
    remove() {
      this.$emit("removed", this.index)
    }
  }
}
</script>

Upvotes: 0

Views: 136

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28414

You have several errors:

  1. v-for should be written like this:
<div
      v-for="(item, index) in items"
      :key="index"
>
  1. props should be defined like this:
props: ["item", "index"],
  1. data() should be written like this:
data() {
    return {
         items: ["sample 1", "sample 2", "sample 3"]
    };
},

Upvotes: 1

Related Questions