【问题标题】:Removing component at index 0 remove all item删除索引 0 处的组件删除所有项目
【发布时间】:2020-09-03 11:29:23
【问题描述】:

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

如果我删除索引 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.js vuejs2 vue-component


    【解决方案1】:

    你有几个错误:

    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"]
        };
    },
    

    【讨论】:

    • 我简化了这里发布的代码,它包含了我认为需要/有错误的所有重要部分。不过,我在真实代码上看不到这些错误。除了删除部分之外,它工作得很好
    • 我测试了您的代码,并在解决上述问题后工作。如果您有任何其他错误,请随时提供您的代码
    猜你喜欢
    • 2021-10-20
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2023-03-10
    • 2018-11-04
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多