vue消息通知实现
Vue 消息通知实现方法
使用第三方库(如Element UI/Toast)
安装Element UI库后,可以直接调用其通知组件:
// 全局引入
import ElementUI from 'element-ui';
Vue.use(ElementUI);
// 使用示例
this.$notify({
title: '提示',
message: '操作成功',
type: 'success'
});
支持多种通知类型(success/warning/info/error),可通过duration参数控制显示时长。
自定义通知组件
创建一个独立的Notification组件:

<template>
<div class="notification" :class="type" v-if="visible">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
visible: false,
message: '',
type: 'info'
}
},
methods: {
show(msg, type = 'info') {
this.message = msg
this.type = type
this.visible = true
setTimeout(() => {
this.visible = false
}, 3000)
}
}
}
</script>
在main.js中全局注册:
import Notification from './components/Notification'
Vue.prototype.$notify = Notification.methods.show
使用Vuex管理通知状态
适合需要跨组件共享通知状态的场景:

// store.js
const store = new Vuex.Store({
state: {
notifications: []
},
mutations: {
addNotification(state, payload) {
state.notifications.push(payload)
},
removeNotification(state, id) {
state.notifications = state.notifications.filter(n => n.id !== id)
}
}
})
组件中调用:
this.$store.commit('addNotification', {
id: Date.now(),
message: '操作成功',
type: 'success'
})
动画效果增强
为通知添加过渡动画:
<transition name="slide-fade">
<Notification v-if="show"/>
</transition>
<style>
.slide-fade-enter-active {
transition: all .3s ease;
}
.slide-fade-leave-active {
transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter, .slide-fade-leave-to {
transform: translateX(10px);
opacity: 0;
}
</style>
服务式调用
创建通知服务模块:
// notification.js
const NotificationService = {
install(Vue) {
const notify = (params) => {
// 创建DOM节点
const NotificationComponent = Vue.extend(Notification)
const component = new NotificationComponent().$mount()
document.body.appendChild(component.$el)
// 显示通知
component.show(params.message, params.type)
}
Vue.prototype.$notify = notify
}
}
export default NotificationService






