首页 > 解决方案 > 删除索引 0 处的组件删除所有项目

问题描述

我在循环中有一个组件,每个组件都有一个删除按钮。

如果我删除索引 1 及以上的组件,它会很好地删除,但是当我删除索引 0(第一个)处的项目时,所有组件都会消失,但数据在 Vue 控制台中仍然可用。

//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>

标签: vue.jsvuejs2vue-component

解决方案


你有几个错误:

  1. v-for应该这样写:
<div
      v-for="(item, index) in items"
      :key="index"
>
  1. props应该这样定义:
props: ["item", "index"],
  1. data()应该这样写:
data() {
    return {
         items: ["sample 1", "sample 2", "sample 3"]
    };
},

推荐阅读