1、弹框组件代码
<template>
<Modal
v-model="visible"
:title="title"
:width="336"
:mask-closable="false"
:styles="style"
:mask="false"
:footer-hide="!hasClose"
@on-cancel="closeModal"
>
<div class="msg-area">
<span>{{ content }}</span>
</div>
<div slot="footer">
<Button @click="closeModal">{{ cancelText }}</Button>
<Button @click="confirmModal" type="primary" v-if="showOk">{{ confirmText }}</Button>
</div>
</Modal>
</template>
<script>
import i18n from "@/plugins/i18n";
export default {
name: "msg-tip",
data() {
return {
visible: false, // 弹框显示
content: "", // 主体内容
hasClose: false, // 关闭按钮
time: 3000, // 自动显示的时间
autoClose: true, // 是否自动关闭
title: i18n.t("component.modal_title"), // 弹框标题
cancelText: i18n.t("component.modal_cancel"), // 关闭按钮描述
showOk: false, // 是否显示确认按钮
confirmText: i18n.t("component.modal_confirm"), // 确认按钮描述
callback: null, // 回调事件
style: {
top: "calc(100% - 200px)",
right: "10px",
position: "absolute"
}
};
},
mounted() {
this.close();
},
methods: {
// 关闭弹框
closeModal() {
this.visible = false;
},
// 确认事件
confirmModal() {
if (this.callback) {
this.callback();
}
this.visible = false;
},
close() {
// 弹框居中显示
if (!this.autoClose && this.hasClose) {
this.style = {};
}
// 默认2s关闭
if (this.autoClose) {
setTimeout(() => {
this.visible = false;
}, this.time);
}
}
}
};
</script>
<style scoped lang="scss">
.msg-area {
margin-bottom: 20px;
}
</style>
2、配置文件
import Vue from "vue";
import Message from "./msg-tip";
const messageBox = Vue.extend(Message);
let msgList = [];
Message.install = function(options) {
if (options === undefined || options === null) {
options = {
content: ""
};
} else if (typeof options === "string" || typeof options === "number") {
options = {
content: options
};
}
const instance = new messageBox({
data: options
}).$mount();
// 隐藏之前的弹框元素
msgList.forEach(m => m.visible && (m.visible = false));
msgList = [];
document.body.appendChild(instance.$el);
msgList.push(instance);
Vue.nextTick(() => {
instance.visible = true;
});
};
export default Message;
3、main.js文件中引入
import Message from "components/msg-tip/index";
Vue.prototype.$msg = Message.install;
4、调用
1、3秒之后自动隐藏
this.$msg("...");
2、点击“关闭”按钮隐藏
this.$msg({
content: "...",
autoClose: false,
hasClose: true
});
3、处理存在“确定”按钮的回调事件
this.$msg({
content: ("确定删除吗?"),
autoClose: false,
hasClose: true,
showOk: true,
callback: this.handleDelete
});