I am creating a ponent to display notifications that should dismiss automatically after a few seconds in Vue, my alert ponents 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.
Vueponent('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?
I am creating a ponent to display notifications that should dismiss automatically after a few seconds in Vue, my alert ponents 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.ponent('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?
- Hint: When an item is removed from an array, what happens to the indices of the items after it? – nnnnnn Commented Mar 27, 2017 at 1:34
- @nnnnnn they reset and start from 0 again, but then how can I delete an specific item if there are no associative arrays in javascript? – enriqg9 Commented Mar 27, 2017 at 1:44
-
2
I don't know enough about Vue to know what the "approved" Vue approach is, but JS does have objects, so perhaps one approach would be to have an array of objects with an
id
andtext
property (or whatever), and in the remove function search the array for the object with the rightid
. – nnnnnn Commented Mar 27, 2017 at 1:50 - @nnnnnn Exactly. – Bert Commented Mar 27, 2017 at 1:54
1 Answer
Reset to default 7As mentioned in the ments, 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.ponent('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.