首页 > 解决方案 > 使用单击事件时,如何以编程方式从 DOM 中删除呈现的 v-for 元素?

问题描述

我正在尝试使用V-Animate-CSS在按下删除按钮时显示“删除”动画。我正在努力尝试指定要在 v-for 循环中以编程方式删除的确切元素。

让我解释:

我有以下vue <template>

  <div
    v-for="x in divisionLangs"
    :key="x.P_uID"
  >

      <button
        type="button"
        @click.prevent="deleteCard(x.P_uID)"
      >
      </button>
    <transition name="bounce"
        <div v-if="show" class="card-body">
            <!-- card content is here -->
        </div>
    </transition>

我的<script>部分如下所示:

data() {
    return {
        show: true,
        divisionLangs: []
    }
}

deleteCard(id) {
  this.show = !this.show
  this.divisionLangs = this.divisionLangs.filter(x => x.P_uID !== id)
},

divisionLangs数组的数据如下所示:

[
  {
    P_uID: 789,
    ..blah...
  },
  {
    P_uID: 889,
    ...blah...
  }
]

如何构造此代码,以便仅从呈现列表中删除匹配的卡片项目,而不是所有卡片项目?现在发生的事情是该deleteCard方法上的所有卡片都被删除了。

标签: vuejs2

解决方案


您应该为每个项目定义一个子组件,如下所示:

父组件:

<tmplate>
    <child-component v-for="x in divisionLangs" :key="x.P_uID" />
</template>

在子组件中:

<button
        type="button"
        @click.prevent="deleteCard(x.P_uID)"
      >
      </button>
    <transition name="bounce"
        <div v-if="show" class="card-body">
            <!-- card content is here -->
        </div>
    </transition>

子组件的脚本部分:

data() {
    return {
        show: true,
        divisionLangs: []
    }
}

deleteCard(id) {
  this.show = !this.show
  this.divisionLangs = this.divisionLangs.filter(x => x.P_uID !== id)
},

推荐阅读