Thursday, 8 June, 2023 UTC


Summary

Users need to stay informed about the status of an application and receive feedback, especially when any asynchronous events occur in the application background. Toast notifications are an effective way to communicate about interface state changes and current progress.
Toast messages contain information that is made visible on screen. They can be dismissible, self-dismissible, or swipeable in nature. Sometimes these distract users from completing their tasks, so they need to be implemented correctly.
In this article, we will walk through some of the best, most used notification libraries for Vue.js. If you want to fork any examples, you can find the GitHub repository here.
We will mainly experiment with three of the most popular Vue notification libraries, and discuss the following:
  • vue-toastification
  • vue-toast-notification
  • vue-sweetalert2
  • When to use toast messages
  • When not to use toast messages
  • Comparison table
vue-toastification
One of the most popular and easy libraries to get started with is vue-toastification. They have the highest number of stars on GitHub, with 2.4k stars. The library can be customized to your application needs, offering different types of content — including text, timeout options, pause when focus out, icon option, sort newest on top — and lot of flexibility.

Features of vue-toastification

  • Compatible with Vue 3
  • Written in TypeScript, with type support
  • Inbuilt swipe-to-close interaction
  • Ability to remove the toast programmatically
  • A window focus() method pause feature
  • Right-to-left and left-to-right text support
You can find a full list of features on GitHub.

Installation

We will install the library with the command below:
npm install --save vue-toastification@next
We can now use the library. Inside our main.js file, we can make the changes below:
import Toast from 'vue-toastification'
import 'vue-toastification/dist/index.css'

//use it 
app.use(Toast)
With the above changes, we can import the Hook provided by the library to help us trigger the toast:
<script>
import { useToast } from "vue-toastification";

export default {
 setup() {
   const toast = useToast();
   return { toast }
 },

 methods: {
   triggerToast() {
     this.toast("Hi from LogRocket", {
       position: "top-right",
       timeout: 5000,
       closeOnClick: true,
       pauseOnFocusLoss: true,
       pauseOnHover: true,
       draggable: true,
       draggablePercent: 0.6,
       showCloseButtonOnHover: false,
       hideProgressBar: true,
       closeButton: "button",
       icon: "fas fa-rocket",
       rtl: false
     });
   }
 }
}
</script>

<template>
 <div>
   <button @click="triggerToast" class="green-button">
     See a notification
   </button>
 </div>
</template>

Creating a custom component

Let’s create a custom component where we can pass the props and other event listeners inside of it. We can pass anything inside the toast (even props, if they’re not reactive) and even close the notification within the toast message itself.
We can do this by limiting our message to just pass strings, so that we can pass anything inside the toast with a custom component; this can be done by simply creating a Vue component.
Create a component and name it Toast.vue:
<script>
export default {
 methods: {
   clicked() {
     // Emit a "click" event when clicked.
     // Can be any event though and even pass parameters back
     this.$emit("click");
   }
 }
};
</script>

<template>
 <div>
   <span>Anything can be added here.</span>
   <button class="action" @click.stop="clicked">Open!</button>
 </div>
</template>
We can import this component to our page and declare it as a custom component, then provide it to the content object as a component key:
seeCustomToast() {
 const content = {
   component: Toast,
   props: {},
   // Listen and react to events using callbacks. In this case we listen for
   // the "click" event emitted when clicking the toast button
   listeners: {
     click: () => {
       this.$toast.success(`Toast notification succeeded`, { position:
             "top-left" })
     }
   }
 }
 this.toast(content);
}
After this change, we can listen for the user’s click in the template using a Vue directive. Then, we’re ready to take a look at the custom toast notification we have created:
<button @click="seeCustomToast" class="green-button">
 See a custom toast notification
</button>
With only this much effort, we have added a simple toast notification and a custom component notification to our application.
vue-toastification in action vue-toast-notification
vue-toast-notification is quite similar to vue-toastification. It’s easy to get started and implement a toast message, but the library offers less by way of customization and flexibility.

Features

  • Support for Vue 3
  • Available as a plugin or via the Composition API
    • The available API methods let you add a few tweaks to your toast message
  • Not fully customizable
  • Dismissable on click
  • No swipe gestures

Installation

Install the library with the command below:
npm install vue-toast-notification@^3.0
Let’s also import the default notification style alongside the library imports:
<script>
import 'vue-toast-notification/dist/theme-bootstrap.css'
import { useToast } from 'vue-toast-notification';

export default {
 setup(){
   const toast = useToast();
   return {toast}
 },
 methods: {
   triggerToast(){
     this.toast.success('You did it!');
   }
 }
}
</script>

<template>
 <div>
   <button class="green-button" @click="triggerToast">
     See a notification
   </button>
 </div>
</template>
With just this much code, we can click to see the toast in the interface:
vue-toast-notification in action vue-sweetalert2
The vue-sweetalert2 library is the Vue version of the popular library sweetalert. This is one of the oldest libraries with vanilla JavaScript support out there, and moreover, this not only adds popovers also popover modals with very little flexibility. It has good community support, with integrations available for three different frameworks. Unfortunately, they are not fully customizable.

Features

  • Supports Vue 3 and TypeScript
  • Less flexibility for custom styling
  • Support for SSR

Installation

Let’s start using the library with the command below:
npm install -S vue-sweetalert2 
Now, import the library:
import VueSweetalert2 from 'vue-sweetalert2';
import 'sweetalert2/dist/sweetalert2.min.css';

app.use(VueSweetalert2)
Now, we can use it in our desired pages. We can call this.$swal and pass few properties as per our need, too:
<script>
 export default{
   methods: {
     triggerToast(){
       this.$swal({
         toast: true,
         position: 'top-end',
         showConfirmButton: false,
         timer: 3000,
         icon: 'success',
         title: 'Hi from Sweetalert',
         text: 'Have a good day ahead!',
         showCancelButton: 'true'
       });
     }
   }
 }
</script>

<template>
 <div>
   <button class="green-button" @click="triggerToast">
     See a notification
   </button>
 </div>
</template>
With this much code, we can trigger a sweetalert toast within our application.
vue-sweetalert2 in action
This might look easy, but it lacks some customizing features in the long run.
When to use toast messages
Toast messages are really useful for communicating with users, but there are some best practices around using them most effectively. We need to be concise and avoid jargon for this type of notification — short, sweet, crisp messages are always ideal.
Toast messages should be easily dismissable or enable the window focus() to make sure users can quickly continue on their path in your app. You should also only use one toast at a time, as they can clutter your app or webpage and distract users. If you’re using toast messages in a mobile use case, consider adding mobile-friendly gestures for dismissal, like tap and swipe.
Here are some use cases when toast messages serve our needs best, such as:
  • On short notice, usually about our application’s system status
  • When offering redirects and alternatives to system failure
  • To confirm a specific action took place like a confirmation, deletion, or editing message
When not to use toast messages
There are also times when we won’t want to make use of toast notifications. The misuse (and overuse) of toast messages can lead to a bad user experience:
  • Displaying confidential information
  • When interrupting the flow
  • Causing distraction
  • Preventing automatic fading toast
  • Non-dismissable
Comparison table
Feature vue-toastification vue-toast-notification vue-sweetalert2
Number of stars 2.4k 477 613
Vue 3 support Yes Yes Yes
Fully customizable Yes Minimal No
Accepts props? Yes No No
Dismissible Yes Yes Yes
Window focus() method Yes No No
Timer Yes Yes No
Drag interaction Yes No No
Official support for other frontend libraries No, similar community libraries available: sswr In-progress, similar community libraries available: vue-query
Conclusion
Toast notifications are a great way to capture user attention and inform them about important application factors. We know toasts should be short-lived and only offer small feedback. Toasts can appear anywhere on the screen, as according to the application’s nature.
You can find the code repository for this post on my GitHub. Thank you.
The post Selecting the best Vue 3 toast notification library appeared first on LogRocket Blog.