8.6 KiB
NotificationDisplay Component
The NotificationDisplay component provides a global notification system for displaying toast-style messages to users. It integrates seamlessly with the notification store to show success, error, warning, and info messages with optional action buttons.
Overview
- Location:
src/components/common/NotificationDisplay.vue - Type: Global Component
- Dependencies:
@/stores/notifications - Integration: Added to
App.vuefor global usage
Features
- ✅ Multiple notification types (success, error, warning, info)
- ✅ Configurable positioning (6 different positions)
- ✅ Auto-dismiss with progress bars
- ✅ Persistent notifications
- ✅ Action buttons with custom handlers
- ✅ Smooth animations (slide-in/out effects)
- ✅ Responsive design
- ✅ Accessibility features
Usage
Basic Integration
The component is automatically included in your application via App.vue:
<template>
<div id="app">
<!-- Your app content -->
<!-- Global Notifications -->
<NotificationDisplay />
</div>
</template>
Triggering Notifications
Use the notification store to display notifications:
import { useNotificationStore } from "@/stores/notifications";
const notificationStore = useNotificationStore();
// Simple success notification
notificationStore.addSuccess("Data saved successfully!");
// Error notification
notificationStore.addError("Failed to save data", "Save Error");
// Custom notification with options
notificationStore.addNotification({
type: "warning",
title: "Unsaved Changes",
message: "You have unsaved changes. What would you like to do?",
persistent: true,
actions: [
{
label: "Save",
variant: "primary",
handler: () => saveData(),
},
{
label: "Discard",
variant: "danger",
handler: () => discardChanges(),
},
],
});
Notification Types
Success
- Color: Green (#10b981)
- Icon: Check circle
- Use case: Successful operations, confirmations
Error
- Color: Red (#ef4444)
- Icon: Alert circle
- Default duration: 6000ms (longer than others)
- Use case: Errors, failures, critical issues
Warning
- Color: Orange (#f59e0b)
- Icon: Alert triangle
- Use case: Warnings, potential issues, confirmations needed
Info
- Color: Blue (#3b82f6)
- Icon: Information circle
- Use case: General information, tips, status updates
Positioning Options
The notification container can be positioned in 6 different locations:
// Set position via notification store
notificationStore.setPosition("top-right"); // Default
// Available positions:
// - 'top-right'
// - 'top-left'
// - 'top-center'
// - 'bottom-right'
// - 'bottom-left'
// - 'bottom-center'
Action Buttons
Notifications can include action buttons for user interaction:
notificationStore.addNotification({
type: "info",
title: "File Upload",
message: "File uploaded successfully. What would you like to do next?",
actions: [
{
label: "View File",
variant: "primary",
icon: "mdi mdi-eye",
handler: (notification) => {
// Custom action logic
console.log("Viewing file from notification:", notification);
},
},
{
label: "Share",
variant: "secondary",
icon: "mdi mdi-share",
handler: () => shareFile(),
dismissAfter: false, // Don't auto-dismiss after action
},
],
});
Action Button Variants
- primary: Blue background
- danger: Red background
- secondary: Gray background (default)
Configuration Options
Global Configuration
const notificationStore = useNotificationStore();
// Set default duration (milliseconds)
notificationStore.setDefaultDuration(5000);
// Set maximum number of notifications
notificationStore.setMaxNotifications(3);
// Set position
notificationStore.setPosition("top-center");
Per-Notification Options
notificationStore.addNotification({
type: 'success',
title: 'Custom Notification',
message: 'This notification has custom settings',
// Duration (0 = no auto-dismiss)
duration: 8000,
// Persistent (won't auto-dismiss regardless of duration)
persistent: false,
// Custom actions
actions: [...],
// Additional data for handlers
data: { userId: 123, action: 'update' }
});
Responsive Behavior
The component automatically adapts to different screen sizes:
- Desktop: Fixed width (320px minimum, 400px maximum)
- Mobile: Full width with adjusted padding
- Positioning: Center positions become full-width on mobile
Animations
The component includes smooth CSS transitions:
- Enter: Slide in from the appropriate direction
- Leave: Slide out in the same direction
- Duration: 300ms ease-out/ease-in
- Progress Bar: Animated countdown for timed notifications
Accessibility Features
- Keyboard Navigation: Buttons are focusable and keyboard accessible
- Screen Readers: Proper ARIA labels and semantic HTML
- Color Contrast: High contrast colors for readability
- Focus Management: Proper focus indicators
Styling
The component uses scoped CSS with CSS custom properties for easy customization:
/* Custom styling example */
.notification-container {
/* Override default styles */
--notification-success-color: #059669;
--notification-error-color: #dc2626;
--notification-warning-color: #d97706;
--notification-info-color: #2563eb;
}
Best Practices
Do's
- ✅ Use appropriate notification types for different scenarios
- ✅ Keep messages concise and actionable
- ✅ Use action buttons for common follow-up actions
- ✅ Set appropriate durations (longer for errors, shorter for success)
- ✅ Use persistent notifications for critical actions requiring user input
Don'ts
- ❌ Don't show too many notifications at once (overwhelming)
- ❌ Don't use persistent notifications for simple confirmations
- ❌ Don't make notification messages too long
- ❌ Don't use error notifications for non-critical issues
Integration with Error Store
The NotificationDisplay component works seamlessly with the Error Store:
import { useErrorStore } from "@/stores/errors";
const errorStore = useErrorStore();
// Errors automatically trigger notifications
await errorStore.withErrorHandling(
"api-call",
async () => {
// Your async operation
},
{
componentName: "myComponent",
showNotification: true, // Automatically shows error notifications
},
);
Examples
Basic Usage Examples
const notificationStore = useNotificationStore();
// Simple notifications
notificationStore.addSuccess("Changes saved!");
notificationStore.addError("Network connection failed");
notificationStore.addWarning("Unsaved changes detected");
notificationStore.addInfo("New feature available");
// Advanced notification with multiple actions
notificationStore.addNotification({
type: "warning",
title: "Confirm Deletion",
message: "This action cannot be undone. Are you sure?",
persistent: true,
actions: [
{
label: "Delete",
variant: "danger",
handler: () => {
performDeletion();
notificationStore.addSuccess("Item deleted successfully");
},
},
{
label: "Cancel",
variant: "secondary",
},
],
});
API Integration Examples
// Show loading notification that updates on completion
const loadingId =
notificationStore.showLoadingNotification("Uploading file...");
try {
await uploadFile();
notificationStore.updateToSuccess(loadingId, "File uploaded successfully!");
} catch (error) {
notificationStore.updateToError(loadingId, "Upload failed: " + error.message);
}
Troubleshooting
Common Issues
-
Notifications not appearing
- Ensure NotificationDisplay is included in App.vue
- Check z-index conflicts with other components
- Verify notification store is properly imported
-
Notifications appearing in wrong position
- Check the position setting in the store
- Verify CSS is not being overridden
-
Action buttons not working
- Ensure handler functions are properly defined
- Check for JavaScript errors in handlers
Debug Mode
Enable debug logging in development:
// In your main.js or component
if (process.env.NODE_ENV === "development") {
const notificationStore = useNotificationStore();
// Watch for notification changes
watch(
() => notificationStore.notifications,
(notifications) => {
console.log("Notifications updated:", notifications);
},
);
}