loading...
Cover image for Vue JS: Notifications with mini-toastr and vue events

Vue JS: Notifications with mini-toastr and vue events

mandrewcito profile image Andrés Baamonde Lozano ・2 min read

On the next develop of my personal website i decided create a toastr notifier. Notifications for javascript have a lot of choices. A cool library is vue-notifications that provides an abstraction from the rest of notifications libraries. But i will not use that library. I decidiced to build a notifications´s library wrapper and make this 'how to'. The notification library i will wrap is mini-toastr

setup

First, we nee install mini toastr library

npm i mini-toastr --save

with library already installed, we need a small edit of our Vue JS main.js

import miniToastr from 'mini-toastr'

miniToastr.init()

Wrapper

No we will code our wrapper. i called the file notificationService.js

import miniToastr from 'mini-toastr'

const notificationService = {
  defaultMessage: {
    type: 'info',
    title: 'default title',
    message: 'default message',
    timeout: 3000, // timeout autohide
    cb: undefined // callback funciton
  },
  types: miniToastr.config.types,
  notify: (apayload) => {
    var payload = { ...notificationService.defaultMessage, ...apayload }
    miniToastr[payload.type](payload.message, payload.title, payload.timeout, payload.cb)
  }
}

export default notificationService

On previous code, i only wrap the library types and i fill payload object with default values ​​if they are not present in it using spread operator.

App.vue

Now we switch to the vue library. We will register our notification event callbacks. Iterate all the types library creating one callback for each type.

<template>
...
</template>

<script>
import notificationService from './notificationService'
export default {
  name: 'App',
  components: {
    ...
  },
  created: function () {
    Object.keys(notificationService.types).forEach(
      (key) => this.$root.$on(
        notificationService.types[key],
        (payload) => notificationService.notify({ ...{ type: notificationService.types[key] }, ...payload })))
  }
}
</script>

Use

Now we create a payload message and emit it with vue events. Our abstractions make possible use the notifications without any library import, and if we change our notification library we only need to reimplement our wrapper.

var payload = {
  type: 'error',
  title: 'funny notifications ! ',
  message: 'default message'
}
this.$root.$emit(payload.type, payload)

Demo

I implemented notifications on my personal website console. Console sends notification with emit and app.vue has registered the operation, so if one is received a notification will be launched.

demo toastr

Thank you for reading me. Feel free for comment any thought below.

References

Vue notifications
Mini toastr
Vue custom events emit
Vue custom events on
Spread operator (...)

Discussion

pic
Editor guide