首页 文章

超时时从数组中删除项目

提问于
浏览
2

我正在创建一个组件来显示应该在Vue中几秒钟后自动解除的通知,我的警报组件发出'过期'事件然后我在父级中侦听此事件,并使用splice从父数据数组中删除它,这有时有效,但有时“警报”不会被删除 .

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

请参阅this Fiddle并多次单击 Create Alert 按钮,并且某些警报不会被解除 . 关于如何解决这个问题的任何想法?

1 回答

  • 2

    正如评论中所提到的,不要通过索引来做到这一点 . 这是另一种选择 .

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

相关问题