vue实现通知
Vue 实现通知功能
使用 Vue 原生特性实现
通过 Vue 的 v-if 或 v-show 控制通知的显示与隐藏,结合动态绑定类名或样式实现动画效果。
<template>
<div>
<button @click="showNotification = true">显示通知</button>
<div v-if="showNotification" class="notification">
这是一条通知
<button @click="showNotification = false">关闭</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showNotification: false
}
}
}
</script>
<style>
.notification {
position: fixed;
bottom: 20px;
right: 20px;
padding: 10px;
background: #42b983;
color: white;
border-radius: 4px;
}
</style>
使用第三方库
Vue 生态中有多个专门用于通知的库,如 vue-notification 或 element-ui 的 Message 组件。
安装 vue-notification:
npm install vue-notification
使用示例:
<template>
<div>
<button @click="showNotification">显示通知</button>
<notifications group="foo" />
</div>
</template>
<script>
import Vue from 'vue'
import Notifications from 'vue-notification'
Vue.use(Notifications)
export default {
methods: {
showNotification() {
this.$notify({
group: 'foo',
title: '重要消息',
text: '这是一条通知'
})
}
}
}
</script>
自定义全局通知组件
创建可复用的全局通知组件,通过 Vue 的事件总线或 Vuex 管理状态。
创建 Notification.vue:
<template>
<div v-if="visible" class="notification">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
visible: false,
message: ''
}
},
methods: {
show(msg) {
this.message = msg
this.visible = true
setTimeout(() => {
this.visible = false
}, 3000)
}
}
}
</script>
注册为全局组件:
import Vue from 'vue'
import Notification from './components/Notification.vue'
const NotificationComponent = Vue.extend(Notification)
const notificationInstance = new NotificationComponent().$mount()
document.body.appendChild(notificationInstance.$el)
Vue.prototype.$notify = notificationInstance.show
使用:
this.$notify('这是一条全局通知')
使用 CSS 动画增强体验
为通知添加进入和离开的动画效果,提升用户体验。
.notification-enter-active, .notification-leave-active {
transition: all 0.5s ease;
}
.notification-enter, .notification-leave-to {
opacity: 0;
transform: translateY(30px);
}
通知队列管理
当需要显示多条通知时,实现一个简单的队列系统。

const notificationQueue = []
let isShowing = false
function showNext() {
if (notificationQueue.length && !isShowing) {
isShowing = true
const { message, duration } = notificationQueue.shift()
this.$notify(message)
setTimeout(() => {
isShowing = false
showNext()
}, duration || 3000)
}
}
export function queueNotification(message, duration) {
notificationQueue.push({ message, duration })
showNext()
}






