Hi I made the following notification component for my vue app where I am looping through errors and success messages from vuex store. I am removing them after 3 seconds from the array. However this means the transition does not gets applied since the element gets removed from the DOM. How can I make that work? Please help me.
<template>
<div
id="toast-container"
>
<div
v-for="(error, index) in errors"
:key="error index"
:
>
<img
svg-inline
src="@/assets/icons/alert_triangle.svg"
alt="alert icon"
>
<div >
<div >
Der er sket en fejl!
</div>
<div >
{{ error }}
</div>
</div>
</div>
<div
v-for="(message, index) in successMessages"
:key="message index"
:
>
<img
svg-inline
src="@/assets/icons/shield_check.svg"
alt="alert icon"
>
<div >
<div >
Succes
</div>
<div >
{{ message }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Notifications',
computed: {
errors() {
return this.$store.state.global.errors
},
successMessages() {
return this.$store.state.global.successMessages
},
},
watch: {
errors: {
handler() {
setTimeout(() => {
this.removeError(0)
}, 3000)
},
deep: true,
},
successMessages: {
handler() {
setTimeout(() => {
this.removeSuccessMessage(0)
}, 3000)
},
deep: true,
},
},
methods: {
removeError(index) {
this.$store.commit('removeError', index)
},
removeSuccessMessage(index) {
this.$store.commit('removeSuccessMessage', index)
},
},
}
</script>
CodePudding user response:
Have a look at https://vuejs.org/guide/built-ins/transition-group.html which is designed for this exact use case. Basically wrapping the whole v-for
block with <TransitionGroup>
and defining proper CSS classes is all you need to do, <TransitionGroup>
will take care of animating the element and removal from DOM after animation is done, you just need to add/remove items from state.