简体   繁体   English

Vue.js 2 - 使用事件中心从数组中删除项目

[英]Vue.js 2 - removing items from array with event hub

I am using Vue.js 2 with Laravel and I have a method inside one component where I send a delete request to the server, and emit the event inside the vue app.我将 Vue.js 2 与 Laravel 一起使用,并且我在一个组件中有一个方法,我在其中向服务器发送删除请求,并在 vue 应用程序中发出事件。 This is the method:这是方法:

deleteAction() {
  let url = `extras/delete/${this.id}`;
  axios.delete(url);
  this.$eventHub.$emit('extras.delete', this.id);
  this.modal.style.display = "none";
}

And in the other component I am listening to the event and removing the item from the array of items that I use to render those items in the template:在另一个组件中,我正在监听事件并从用于在模板中呈现这些项目的项目数组中删除该项目:

<template>
  <div>
    <div v-for="item in items" class="media row">
      <div class="media-left col-sm-3">
        <a href="#">
          <img class="media-object" :src="item.image_path" :alt="item.title">
        </a>
      </div>
      <div class="media-body col-sm-6">
        <h4 class="media-heading">{{ item.title }}</h4>
        <p>{{ item.description }}</p>
      </div>
      <div class="col-sm-3 action-buttons">
        <a class="btn btn-info" href="/extras/create" role="button">Rediger</a>
        <alert :id="item.id"></alert>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  props: ['items'],
  data () {
    return {}
  },
  created() {
      this.$eventHub.$on('extras.delete',(id) => {
          this.items = this.items.filter(function(el) {
            return el.id !== id;
          });
      })
  }
}
</script>

But, even though I see the event happening in the debug tools under the events, the first item is only removed after the second attempt, and the all other items after the first one are removed normally with the first attempt.但是,即使我在事件下的调试工具中看到事件发生,第一个项目仅在第二次尝试后被删除,第一个项目后的所有其他项目在第一次尝试时正常删除。 Why is this happening?为什么会这样?

try adding key attribute.尝试添加关键属性。 check the docs for more details https://v2.vuejs.org/v2/guide/list.html#key检查文档以获取更多详细信息https://v2.vuejs.org/v2/guide/list.html#key

    <template>
  <div>
    <div v-for="item in items" :key="item.id" class="media row">
      <div class="media-left col-sm-3">
        <a href="#">
          <img class="media-object" :src="item.image_path" :alt="item.title">
        </a>
      </div>
      <div class="media-body col-sm-6">
        <h4 class="media-heading">{{ item.title }}</h4>
        <p>{{ item.description }}</p>
      </div>
      <div class="col-sm-3 action-buttons">
        <a class="btn btn-info" href="/extras/create" role="button">Rediger</a>
        <alert :id="item.id"></alert>
      </div>
    </div>
  </div>
</template>

将 console.log 放入创建的句柄和事件订阅者方法中,并检查您是否第一次获得所需的 id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM