Skip to content

Instantly share code, notes, and snippets.

@ecmel
Last active February 19, 2018 12:25
Show Gist options
  • Save ecmel/de3db7031222e9a89f1d628ed8f18cdd to your computer and use it in GitHub Desktop.
Save ecmel/de3db7031222e9a89f1d628ed8f18cdd to your computer and use it in GitHub Desktop.
Pure Vue Bootstrap 4 Toastr
<script>
export default {
data() {
return {
toasts: [],
timeout: 3000
}
},
created() {
this.$root.$on('toast', this.toast)
},
beforeDestroy() {
this.$root.$off('toast', this.toast)
},
methods: {
toast(toast) {
toast.id = Date.now()
this.toasts.unshift(toast)
setTimeout(() => {
this.close(toast)
}, this.timeout)
},
close(toast) {
for (let i = this.toasts.length - 1; i >= 0; i--) {
if (this.toasts[i].id === toast.id) {
this.toasts.splice(i, 1)
break
}
}
}
}
}
</script>
<template>
<div class="toastr">
<transition-group name="toastr">
<div class="toastr-toast alert"
:class="{
'alert-success': toast.severity === 0,
'alert-info': toast.severity === 1,
'alert-warning': toast.severity === 2,
'alert-danger': toast.severity === 3
}"
v-for="toast in toasts"
:key="toast.id"
@click="close(toast)">
{{ toast.msg }}
</div>
</transition-group>
</div>
</template>
<style>
.toastr {
position: fixed;
width: 18rem;
top: 1rem;
right: 1rem;
cursor: default;
z-index: 9999;
}
.toastr-toast {
width: 18rem;
transition: all .5s;
}
.toastr-enter {
opacity: 0;
transform: translateY(-3rem);
}
.toastr-leave-to {
opacity: 0;
transform: translateX(18rem);
}
.toastr-leave-active {
position: absolute;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment