实现vue message
实现 Vue Message 组件
Vue Message 组件通常用于全局消息提示,类似于 Element UI 的 this.$message。以下是实现方法:
1. 创建 Message 组件

<template>
<transition name="message-fade">
<div v-if="visible" class="message" :class="[type]">
{{ message }}
</div>
</transition>
</template>
<script>
export default {
name: 'Message',
data() {
return {
message: '',
type: 'info',
visible: false,
duration: 3000
}
},
mounted() {
this.show()
},
methods: {
show() {
this.visible = true
setTimeout(() => {
this.hide()
}, this.duration)
},
hide() {
this.visible = false
setTimeout(() => {
this.$destroy()
this.$el.remove()
}, 500)
}
}
}
</script>
<style scoped>
.message {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
padding: 10px 20px;
border-radius: 4px;
z-index: 9999;
}
.message.info {
background-color: #f4f4f5;
color: #909399;
}
.message.success {
background-color: #f0f9eb;
color: #67c23a;
}
.message.error {
background-color: #fef0f0;
color: #f56c6c;
}
.message.warning {
background-color: #fdf6ec;
color: #e6a23c;
}
.message-fade-enter-active,
.message-fade-leave-active {
transition: all 0.3s;
}
.message-fade-enter,
.message-fade-leave-to {
opacity: 0;
transform: translate(-50%, -20px);
}
</style>
2. 创建插件入口
import Vue from 'vue'
import Message from './Message.vue'
const MessageConstructor = Vue.extend(Message)
const message = (options) => {
if (typeof options === 'string') {
options = {
message: options
}
}
const instance = new MessageConstructor({
data: options
})
instance.$mount()
document.body.appendChild(instance.$el)
return instance
}
const types = ['success', 'warning', 'info', 'error']
types.forEach(type => {
message[type] = options => {
if (typeof options === 'string') {
options = {
message: options
}
}
options.type = type
return message(options)
}
})
export default message
3. 在 main.js 中全局注册

import Vue from 'vue'
import message from './plugins/message'
Vue.prototype.$message = message
4. 使用示例
// 普通用法
this.$message('这是一条消息')
// 带类型
this.$message.success('成功消息')
this.$message.error('错误消息')
this.$message.warning('警告消息')
this.$message.info('提示消息')
// 带配置
this.$message({
message: '自定义消息',
type: 'success',
duration: 5000
})
5. 高级功能扩展
- 添加关闭按钮
- 支持多消息同时显示
- 支持 HTML 内容
- 支持手动关闭
- 支持位置配置(顶部/底部/中间)
这个实现提供了基本的 Message 功能,可以根据项目需求进一步扩展和完善。






