简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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