How to setup Toast notifications in VueJS application

6a546f5c3a244dc54f00ac073e75ab73.jpeg

Notifications are a powerful tool for developers to increase app interactivity and improve user experience. By utilizing notifications, developers can effectively communicate important events to users while they are interacting with the application.

Notifications play a vital role in an application to inform users about various actions and events in a timely manner. They can be used to notify users of task failures, network outages, successful operations, warnings, errors, and important information. These notifications serve as valuable updates, ensuring users are aware of ongoing events and the necessary actions they need to take.

Why are notifications important?

Notifications are everywhere and can take various forms, including email or text message notifications, as well as in-app notifications, which this article will focus on. In-app notifications are a valuable tool in a variety of situations, such as:

  • Notify users of validation errors: In-app notifications can promptly alert users to any validation errors they may encounter while interacting with your app, making sure they know of any issues that require attention.

  • Communicate success, errors, or warnings: In-app notifications provide a way to communicate important feedback to users about the results of their actions. Whether confirming a successful operation, indicating an error that needs to be resolved, or providing a warning, these notifications keep users informed about the status of their operation.

  • Handling network failures: When network failures occur, in-app notifications can inform users about temporary outages, allowing them to understand the situation and possibly adjust usage or expectations accordingly.

  • Provide progress reports: In-app notifications can act as progress indicators to keep users informed of the status of long-running processes or tasks. By showing regular updates, users can see progress, which helps manage expectations and provides a sense of peace of mind.

  • Share informational messages: In-app notifications are an effective means of conveying important information or updates to users. Whether informing about new features, policy changes, or other relevant information, these notifications keep users informed and engaged with your app.

We will not develop a popup notification from scratch. Instead, we'll leverage the vue-toastification library. This lightweight and customizable library offers out-of-the-box TypeScript support and easy setup.

set up

The code in this guide was built and tested with Vue.js version 3.3.2, but it should work with other versions of Vue.js as well.

To start using Vue.js, you can use the command npm init vue@latest to create a new Vue.js application, or include it in your existing Vue.js application.

Note: Make sure you have Node.js version 16.0 or later installed.

Install

Depending on your preferred package manager, you can install vue-toastification in Vue.js with the following command.

npm add vue-toastification@next

//or 

yarn add vue-toastification@next

This command will install the dependencies that vue-toastification needs to run on your system.

To integrate vue-toastification into your application, find the main.js or main.ts file in the root directory of your application. Include the code snippet below in this file as it is the entry point of your Vue.js application. Here you can register the library and configure it according to your requirements.

import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
//import the Toast library here
import Toast from "vue-toastification"
import "vue-toastification/dist/index.css";

import App from './App.vue'
import router from './router'

const ToastOptions = {
    // your default options goes here
};

const app = createApp(App)

app.use(createPinia())
app.use(router)
//register the Toast plugin for global use in the application.
app.use(Toast, ToastOptions)

app.mount('#app')

Creating toasts

We'll declare various functions for the success, error, warning, info, and normal tooltip functions so that we can easily import them into components that need them and use them there. This is more helpful than importing the same thing over and over. It will make our code cleaner, avoid repetition, and make it easier to maintain.

In your src directory, create a folder named util, and then create a file named toast.ts in it, you can write the code shown below in this file.

import { useToast } from "vue-toastification";
import type { ToastID } from "vue-toastification/dist/types/types";

const toast = useToast();
const defaultToastMessage = "Toastification is awesome";

export function normalToast(message: string): ToastID {
    if (!message) {
        return toast(defaultToastMessage);
    }
    return toast(message);
}

export function success(message: string): ToastID {
    if (!message) {
        return toast(defaultToastMessage);
    }
    return toast.success(message);
}

export function warning(message: string): ToastID {
    if (!message) {
        return toast(defaultToastMessage);
    }
    return toast.warning(message);
}

export function error(message: string): ToastID {
    if (!message) {
        return toast(defaultToastMessage);
    }
    return toast.error(message);
}

export function info(message: string): ToastID {
    if (!message) {
        return toast(defaultToastMessage);
    }
    return toast.info(message);
}

Now in our Vuejs component, we can explicitly import the toast notification function we need, and pass the message we want to toast.

To test it, go to the App.vue component and import the success function from util as follows.

<script setup lang="ts">
import { normalToast , success } from "@/utils/toast"
import { onMounted } from 'vue';

onMounted( () => {

  normalToast("Normal toast message")

  success("Success toast message")
})
</script>

When our component is mounted, we can see a popup notification in the application. In a real project, this use case might be unnecessary, since we want the notification to pop up under certain conditions, not when the component is mounted.

Customize prompt information

You can customize the prompt information according to your personal preferences and usage. We can also add some additional customization options, such as setting a timeout for the prompt message, closing the prompt message programmatically, and so on.

Set a timeout for prompts

We can set how long toast notifications stay on the page, or allow users to dismiss them by clicking the X icon. Depending on your use case, you can set it up as shown below.

Allow users to dismiss popup messages

// allow the user to dismiss the message by cling the x icon on the toast
export function success(message: string): ToastID {
    if (!message) {
        return toast(defaultToastMessage);
    }
    return toast.success(message, {timeout: false});
}

Cancel popup prompt after X seconds timeout

// dismiss the toast after 3 seconds
export function success(message: string): ToastID {
    if (!message) {
        return toast(defaultToastMessage);
    }
    return toast.success(message, {timeout: 3000);
}

There are many configuration options to customize. Check out Vuejs Toastification for all possible customization options.

Finish

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of articles is not easy. If you like my sharing, please don’t forget to like and forward it, so that more people in need See. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

おすすめ

転載: blog.csdn.net/Ed7zgeE9X/article/details/132680109