实现vue message
实现 Vue 消息提示组件
创建 Message 组件
在 src/components 目录下创建 Message.vue 文件,内容如下:
<template>
<transition name="fade">
<div v-if="visible" class="message" :class="type">
{{ content }}
</div>
</transition>
</template>
<script>
export default {
data() {
return {
visible: false,
content: '',
type: 'info'
}
},
methods: {
show(content, type = 'info', duration = 3000) {
this.content = content
this.type = type
this.visible = true
setTimeout(() => {
this.visible = false
}, duration)
}
}
}
</script>
<style scoped>
.message {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
padding: 10px 20px;
border-radius: 4px;
color: white;
z-index: 9999;
}
.info {
background-color: #1890ff;
}
.success {
background-color: #52c41a;
}
.warning {
background-color: #faad14;
}
.error {
background-color: #f5222d;
}
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
创建插件文件
在 src/plugins 目录下创建 message.js 文件:

import Vue from 'vue'
import Message from '@/components/Message.vue'
const MessageConstructor = Vue.extend(Message)
const message = (options = {}) => {
const instance = new MessageConstructor({
data: options
})
instance.$mount()
document.body.appendChild(instance.$el)
instance.show(options.content, options.type, options.duration)
}
export default {
install(Vue) {
Vue.prototype.$message = message
}
}
注册插件
在 main.js 中注册插件:
import Vue from 'vue'
import Message from '@/plugins/message'
Vue.use(Message)
使用方式 在组件中调用:

this.$message({
content: '这是一条提示消息',
type: 'success',
duration: 2000
})
// 或简写形式
this.$message.success('操作成功')
this.$message.error('操作失败')
扩展方法
在 message.js 中添加快捷方法:
['success', 'warning', 'info', 'error'].forEach(type => {
message[type] = (content, duration = 2000) => {
return message({
content,
type,
duration
})
}
})
全局挂载
如果需要全局挂载而非在每个组件中通过 this 调用:
// 在 message.js 中
const message = {
install(Vue) {
Vue.prototype.$message = messageFunction
}
}
// 在 main.js 中
import message from '@/plugins/message'
Vue.use(message)
window.message = message






