Implementing a notification system in Vue has been my latest project. I've created a Notifications component to store error messages that I want to display.
data(){
return {
alerts: {
error: []
}
}
}
Whenever an event occurs in the root component, I add a message to the error array and then loop through them in the Notification template.
<transition-group name="slide-fade">
<Error v-for="(alert, index) in alerts.error" :key="index" :alert="alert" @removeError="removeError($event)"></Error>
</transition-group>
In the Error component, each message is displayed along with a closing button.
**The challenge now is setting these messages to automatically close after 3 seconds. **
Here's how the Error component looks:
<template>
<div class="alert alert-danger alert-dismissible" role="alert">
{{alert.msg}}
<button ref="closeButton" type="button" class="close" @click.prevent="remove()">
<span aria-hidden="true">×</span>
</button>
</div>
</template>
<script>
export default {
props: ["alert"],
methods: {
remove(){
this.$emit("removeError", this.$props.alert);
}
},
mounted(){
setTimeout(() => {
this.remove();
}, 3000);
}
}
</script>
I trigger the removal either by clicking on the button or after 3 seconds with a setTimeout function. The event is caught back in the Notification component, where a method is called to filter out the message from the initial array:
removeError(toRemove){
this.alerts.error = this.alerts.error.filter(item => {
return item !== toRemove;
});
}
The problem arises when having multiple errors pushed in the array and waiting for the timeout. Only some of those messages get filtered (like 2 or 3 out of 5), while others remain in the array.
Check out images of the result here:
Errors remaining after the timeout
An Update on the Issue:
The issue was caused by using keys in the Error component - Vue would get confused as the key of the array recalculates when an element is removed.
This led to another problem because Vue only accepts primitive keys, meaning they have to be either strings or numbers. But all I have as a key is the message itself, which might not always be unique, especially if two messages are the same. Any suggestions on how to overcome this challenge?