简体   繁体   中英

Remove item from array on timeout

I am creating a component to display notifications that should dismiss automatically after a few seconds in Vue, my alert components emits an 'expired' event and then I listen for this event in the parent, and remove it from the parent data array with splice, this works sometimes but sometimes the 'alerts' are not removed.

Vue.component('alert', {
  template: '<li><slot></slot></li>',
  mounted() {
    setTimeout(() => this.$emit('expired'), 2000)
  }
});

new Vue({
  el: '#app',
  data: {
    count: 0,
    alerts: []
  },
  methods: {
        createAlert(){
        this.alerts.push(this.count++)
      },
      removeItem(index) {
        this.alerts.splice(index, 1)
      }
  }
});

See this Fiddle and click on the Create Alert button a couple of times, and some of the alerts won't get dismissed. Any ideas on how to solve this?

As mentioned in the comments, don't do this by index. Here is one alternative.

<div id="app">
  <button @click="createAlert">
    Create Alert
  </button>
  <alert v-for="(alert, index) in alerts" :key="alert.id" :alert="alert" @expired="removeItem(alert)">{{ alert.id }}</alert>
</div>

Vue.component('alert', {
  props: ["alert"],
  template: '<li><slot></slot></li>',
  mounted() {
    setTimeout(() => this.$emit('expired', alert), 2000)
  }
});

new Vue({
  el: '#app',
  data: {
    count: 0,
    alerts: []
  },
  methods: {
        createAlert(){
        this.alerts.push({id: this.count++})
      },
      removeItem(alert) {
        this.alerts.splice(this.alerts.indexOf(alert), 1)
      }
  }
});

Your fiddle revised .

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