消息弹框
- 支持自定义消息内容
- 支持指定消息弹窗的停留时间
<template>
<div class="xx-message-box"></div>
</template>
<script>
export default {
props: {
message: String,
stayTime: {
type: Number,
default: 3000
}
},
mounted() {
setTimeout(() => {
this.$destroy();
}, this.stayTime);
}
};
</script>
<style>
.xx-message-box {
position: fixed;
left: 0;
right: 0;
margin: auto;
width: fit-content;
z-index: 9999999;
padding: 5px;
background: #e8f3ff;
color: var(--juejin-brand-1-normal);
border-radius: 5px;
white-space: pre-wrap;
line-height: 1.8;
}
</style>
以全局函数的方式使用
import Vue from 'vue';
const MessageConstructor = Vue.extend(Message);
export function message(options) {
if (typeof options === 'string') {
options = { message: options };
}
const instance = new MessageConstructor({ propsData: options });
instance.$on('hook:mounted', function() {
document.body.appendChild(this.$el);
});
instance.$on('hook:destroyed', function() {
this.$el.remove();
});
instance.$mount();
}
需要在弹窗关闭后做一些事
export function message(options) {
return new Promise(resolve => {
if (typeof options === 'string') {
options = { message: options };
}
const instance = new MessageConstructor({ propsData: options });
instance.$on('hook:mounted', function() {
document.body.appendChild(this.$el);
});
instance.$on('hook:destroyed', function() {
this.$el.remove();
resolve();
});
instance.$mount();
});
}
使用队列处理同时有多条消息
const messageQueue = [];
let currentMessage = null;
function handleNextMessage() {
currentMessage = messageQueue.shift();
currentMessage?.$mount();
}
export function message(options) {
return new Promise(resolve => {
if (typeof options === 'string') {
options = { message: options };
}
const instance = new MessageConstructor({ propsData: options });
instance.$on('hook:mounted', function() {
document.body.appendChild(this.$el);
});
instance.$on('hook:destroyed', function() {
this.$el.remove();
handleNextMessage();
resolve();
});
if (currentMessage) {
messageQueue.push(instance);
} else {
currentMessage = instance;
instance.$mount();
}
});
}