[Vuejs]-Vue.js $emit not received by parent when multiple calls in short amount of time

2👍

my small fiddle from back in the days is still making the rounds I see 😀

That fiddle is still using Vue 1. In Vue 2, you have to key your list elements, and you tried to do that.

But a key should be a unique value identifying a data item reliably. You are using the array index, which does not do that – as soon as an element is removed, indices of the following items change.

That’s why you see the behaviour you are seeing: Vue can’t reliably remove the right element because our keys don’t do their job.

So I would suggest to use a package like nanoid to create a really unique id per notification – but a simple counter would probably work as well:

let _id = 0
class NotificationStore {
  constructor () {
    this.state = {
      notifications: []
    }
  }
  addNotification (notification) {    
    this.state.notifications.push({ ...notification, id: _id++ })
  }
  removeNotification (notification) {
    console.log('remove from store')
    this.state.notifications.splice(this.state.notifications.indexOf(notification), 1)
  }
}

and in the notification component:

<notification-message 
  v-for="(notification, index) in notifications" 
  :notification="notification" 
  :key="notification.id"
  v-on:closeNotification="removeNotification"
></notification-message>

Leave a comment