How to Display Toast Messages and Notifications Using `$message` and `$notify` in Element UI
Element UI registers $message and $notify as global methods on the Vue prototype during installation, allowing any component to show lightweight toasts or rich system notifications with a single method call.
If you are building Vue applications with the ElemeFE/element component library, you can display toast messages and notifications using $message and $notify without importing components into every file. These helper methods are injected into every Vue instance during the library's initialization, providing immediate access to stackable, auto-positioning feedback UI.
How $message and $notify Are Registered in Element UI
Both utilities become globally available when you install Element UI. In src/index.js, the library explicitly attaches the Message and Notification constructors to Vue.prototype:
// src/index.js
Vue.prototype.$notify = Notification;
Vue.prototype.$message = Message;
This registration pattern means any Vue component can access these methods via this.$message or this.$notify to trigger toast messages or notification panels from anywhere in your application logic.
Using $message for Toast Notifications
The $message helper creates lightweight, self-dismissing feedback toasts that appear at the top center of the viewport. The core implementation resides in packages/message/src/main.js, which manages instance creation, vertical stacking, and automatic cleanup.
Basic String Usage
Pass a string directly to show a simple message:
this.$message('This is a simple message.');
Typed Message Shortcuts
For semantic coloring, use the type-specific static methods:
this.$message.success('Operation successful!');
this.$message.warning('Warning: Check your inputs.');
this.$message.error('Error: Something went wrong.');
this.$message.info('This is an informational note.');
Advanced Configuration
Control duration, closability, and HTML rendering via an options object:
this.$message({
message: '<strong>Saved successfully</strong>',
type: 'success',
showClose: true,
duration: 0, // 0 means it stays until manually closed
dangerouslyUseHTMLString: true // allows HTML in the message
});
Under the hood, each call generates a unique ID (message_<seed>), calculates a verticalOffset based on existing instances, and appends the toast to document.body.
Using $notify for System Notifications
The $notify helper produces richer notification cards that support titles, positioning in any corner, and independent stacking per position. The implementation in packages/notification/src/main.js mirrors the Message architecture but adds multi-position support.
Positioned Notifications
Unlike messages that stack top-center, notifications can appear in four corners:
this.$notify({
title: 'Update Available',
message: 'Version 2.0 is ready to install.',
position: 'bottom-left', // options: top-right, top-left, bottom-right, bottom-left
type: 'info',
duration: 8000
});
Notification Shortcuts
Similar to $message, you can use typed shortcuts:
this.$notify.success({
title: 'Success',
message: 'Data saved successfully.'
});
// Or shorthand with just a string
this.$notify.error('Critical failure occurred!');
The library maintains separate instance arrays for each position value, calculating offsets independently so that top-right notifications do not interfere with bottom-left stacks.
Managing the Notification Stack and Lifecycle
Both $message and $notify manage their own DOM instances through internal instances arrays. When you call either method, the utility:
- Creates a Vue-extended component from the respective
.vuefile - Generates a unique ID using an internal seed counter
- Calculates the
verticalOffsetby summing the heights of existing items plus a default gap (20px for messages, 16px for notifications) - Mounts the element to
document.body
Programmatic Closing
Each call returns the component instance, allowing manual control:
// Show a persistent toast
const toast = this.$message({
message: 'Processing...',
duration: 0
});
// Close it programmatically later
toast.close();
To dismiss all active notifications globally:
Message.closeAll(); // closes all toasts
Notification.closeAll(); // closes all notifications regardless of position
The close(id, userOnClose) method removes the specific instance from its internal array and triggers a repositioning of remaining items to fill the vertical gap.
Complete Code Examples
Basic Vue Component with Toast
<template>
<el-button @click="showToast">Show Toast</el-button>
</template>
<script>
export default {
methods: {
showToast() {
this.$message({
message: 'Changes saved!',
type: 'success'
});
}
}
}
</script>
Notification with HTML Content
this.$notify({
title: 'Danger',
message: '<strong>Server Error:</strong> Connection timeout',
type: 'error',
dangerouslyUseHTMLString: true,
position: 'top-left',
duration: 5000
});
Dynamic Stack Management
// Create multiple messages
const msg1 = this.$message({ message: 'First', duration: 0 });
const msg2 = this.$message({ message: 'Second', duration: 0 });
// Close specific one
setTimeout(() => msg1.close(), 2000);
// Or clear everything
setTimeout(() => Message.closeAll(), 5000);
Summary
- Global Registration: Element UI attaches
$messageand$notifytoVue.prototypeinsrc/index.js, making them available in every component. - Implementation Paths: Message logic lives in
packages/message/src/main.js; Notification logic resides inpackages/notification/src/main.js. - API Flexibility: Both helpers accept strings, VNodes, or options objects, and provide shortcut methods for
success,warning,error, andinfotypes. - Stack Management: Instances track their own IDs and vertical offsets, automatically repositioning remaining items when one closes.
- Programmatic Control: Returned instances expose a
close()method, whileMessage.closeAll()andNotification.closeAll()clear entire stacks.
Frequently Asked Questions
What is the difference between $message and $notify in Element UI?
$message displays lightweight toast banners that appear at the top center and automatically disappear after a set duration. $notify creates richer notification cards that support titles, custom positioning in any screen corner, and typically remain visible longer. Choose $message for brief feedback and $notify for system-level alerts requiring user attention.
How do I prevent a toast or notification from closing automatically?
Set the duration property to 0 in the options object. This keeps the message or notification visible until the user clicks the close button or you call the instance's close() method programmatically. You should also set showClose: true to ensure users have a way to dismiss the element.
Can I use HTML inside Element UI toast messages and notifications?
Yes, both $message and $notify support HTML content when you set dangerouslyUseHTMLString: true in the options object. Pass your HTML string to the message property. Be cautious when rendering user-generated content to avoid XSS vulnerabilities.
How do I position notifications in corners other than the default top-right?
Use the position property in the options object passed to $notify. Valid values are 'top-right', 'top-left', 'bottom-right', and 'bottom-left'. Each position maintains its own independent stack, allowing notifications to accumulate separately in different corners of the screen.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →