How to create dynamic Toast Notification component in Vue.js
What is a “Toast Notification”
The term toast notification (or snackbar notification) or simply notification refers to a graphical control element that communicates certain events to the user without forcing them to react to this notification immediately, unlike conventional pop-up windows.
In this article, we will be creating a dynamic toast notification component that displays information to the user based on the type of feedback that is coming from the application (i.e Success, Info or Error) using Vue.js and Vite (https://vitejs.dev).
Who is this article for?
This article is meant for people like myself who don’t like installing an npm package for every little functionality. I have nothing against npm packages, but why over-bloat your code base for basic functionalities you can implement natively? not to mention the security vulnerabilities that come with some of these packages.
Prerequisites:
Basic knowledge of the following is required in order to get the best out of this article.
- Vue.js (version 3)
- TailwindCSS
- Pinia (for state management)
- Node.js (Version ≥14)
- An IDE (doesn’t have to be VSCode 🤪)
Project setup
If you’d like to follow along with this project (and I highly recommend you do), clone the starter project from github repo using 👇🏻 command
git Clone https://github.com/abugi/vue-toast-notification.git
Check into the cloned folder with 👇🏻 command
cd vue-toast-notification
Now install the project dependencies to roundup the setup process.
This can be achieved by running 👇🏻 command
npm install
If you followed the setup correctly, you should end up with a “package.json” file that looks like 👇🏻
Let’s start building
STEP 1: Create the Toast component
Create “AppToast.vue” file in the “components” directory and add 👇🏻
STEP 2: Create our base component
Open “App.vue” file in the “src” directory and replace the code with 👇🏻
STEP 3: Create reusable button component
Create “AppButton.vue” file in the “components” directory and add 👇🏻
STEP 4: Create a central store with Pinia state management library
We used Pinia here in order to make data globally available throughout our application.
Create a “stores” directory in “src” folder.
Inside the “stores” directory, create a file “toast.js” and add the following code…
The code above basically creates a new Pinia store and defines the state data that will be used by our components. You can read more about Pinia on the official Pinia website.
The complete code can be found here
Happy coding 🤡