簡體   English   中英

超時時從陣列中刪除項目

[英]Remove item from array on timeout

我正在創建一個組件,以顯示在Vue中幾秒鍾后應自動關閉的通知,我的警報組件會發出“過期”事件,然后我在父級偵聽此事件,並使用拼接將其從父級數據數組中刪除,有時可以使用,但有時不會刪除“警報”。

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)
      }
  }
});

看到此小提琴 ,然后單擊“ Create Alert按鈕兩次,某些警報將不會消失。 關於如何解決這個問題的任何想法?

如評論中所述,請勿按索引執行此操作。 這是一種選擇。

<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)
      }
  }
});

你的小提琴修訂了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM