Hệ thống thông báo toàn cục (Global Notifications), bạn sẽ học cách tạo thông báo dạng toast để hiển thị các sự kiện như:
- Thêm thành công
- Lỗi hệ thống
- Đăng nhập thành công
- Nhắc người dùng hành động
Đây là một phần cực kỳ cần thiết trong ứng dụng thực tế để nâng cao trải nghiệm người dùng.
Mục tiêu:
- Tạo store
notificationStore
bằng Pinia - Tạo component
<ToastNotification />
- Cho phép hiển thị nhiều toast (xếp chồng)
- Tự động ẩn sau vài giây
Phần 1: Tạo Store quản lý toast
src/store/notificationStore.js
import { defineStore } from 'pinia'
export const useNotificationStore = defineStore('notification', {
state: () => ({
toasts: []
}),
actions: {
notify(message, type = 'info') {
const id = Date.now()
this.toasts.push({ id, message, type })
setTimeout(() => {
this.toasts = this.toasts.filter(t => t.id !== id)
}, 3000)
}
}
})
Phần 2: Tạo component Toast UI
src/components/ToastNotification.vue
<template>
<div class="toast-container">
<div
v-for="toast in toasts"
:key="toast.id"
class="toast"
:class="toast.type"
>
{{ toast.message }}
</div>
</div>
</template>
<script setup>
import { useNotificationStore } from '@/store/notificationStore'
import { storeToRefs } from 'pinia'
const store = useNotificationStore()
const { toasts } = storeToRefs(store)
</script>
<style scoped>
.toast-container {
position: fixed;
top: 20px;
right: 20px;
z-index: 9999;
display: flex;
flex-direction: column;
gap: 10px;
}
.toast {
padding: 10px 16px;
border-radius: 6px;
color: white;
animation: slide-in 0.3s ease-out;
}
.toast.info {
background: #3498db;
}
.toast.success {
background: #2ecc71;
}
.toast.error {
background: #e74c3c;
}
@keyframes slide-in {
from {
opacity: 0;
transform: translateX(30px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
</style>
Phần 3: Dùng toast trong toàn app
App.vue
<template>
<router-view />
<ToastNotification />
</template>
<script setup>
import ToastNotification from './components/ToastNotification.vue'
</script>
Phần 4: Cách gọi thông báo từ bất kỳ nơi nào
Ví dụ trong authStore.js
:
import { useNotificationStore } from './notificationStore'
// bên trong action login:
const notify = useNotificationStore().notify
notify('Đăng nhập thành công!', 'success')
// hoặc khi lỗi:
notify('Sai tài khoản hoặc mật khẩu!', 'error')
Tương tự, bạn có thể thêm notify(...)
trong:
todoStore
: khi thêm, xóa todoAccountView
: khi đổi mật khẩuApp.vue
: khi có lỗi toàn cục từ mạng
Kỹ năng | Vai trò |
---|---|
Pinia store global | Quản lý danh sách toast |
<ToastNotification /> | Hiển thị UI đẹp, tự động ẩn |
Reusability | Dùng ở bất kỳ đâu trong app |
UX nâng cao | Người dùng có phản hồi trực tiếp |
- Cho phép toast có icon (theo loại)
- Làm animation mượt hơn (dùng
@vueuse/motion
) - Cho toast kéo để tắt hoặc click tắt thủ công
Thảo luận