借鉴原文链接: https://blog.csdn.net/qq_45780736/article/details/127569860
基于Ant Design的Modal重新封装了一个$confirm全局弹窗组件,效果如下
先写一个弹窗组件,index.vue
我在此处直接使用了antdesgin的modal组件,也可以直接自己写样式
<template>
<a-modal
:title="title"
:visible="showMsgBox"
:mask-closable="false"
:confirm-loading="false"
:cancel-text="cancelText"
:ok-text="okText"
width="480px"
@ok="confirmMsg"
@cancel="cancleMsg">
<div class="msg-tip">
<span class="msg-icon"><a-icon type="exclamation-circle" theme="filled" /></span>
<span class="msg-title">{{ content }}</span>
<div class="msg-sub-title">{{ subContext }}</div>
</div>
</a-modal>
</template>
<script>
export default {
name: 'MsgBox',
data() {
return {
title: '',
content: '',
subContext: '',
showMsgBox: false,
onOk: '',
onCancle: '',
okText: '',
cancelText: ''
}
},
methods: {
open({ title, content, subContext, msgType = 1, onOk, onCancle, okText, cancelText }) {
this.showMsgBox = true
this.msgType = msgType
this.title = title
this.content = content
this.subContext = subContext
this.onOk = onOk
this.onCancle = onCancle
this.okText = okText
this.cancelText = cancelText
},
confirmMsg() {
this.showMsgBox = false
this.onOk()
// 组件关闭后销毁该组件
this.remove()
},
cancleMsg() {
this.showMsgBox = false
this.onCancle && this.onCancle()
// this.remove()
}
}
}
</script>
<style lang="less" scoped >
.msg-tip {
.msg-icon {
margin-right: 16px;
font-size: 22px;
float: left;
margin-top: -5px;
color: #faad14
}
.msg-title {
color: rgba(0,0,0,.85);
font-weight: 500;
font-size: 16px;
line-height: 1.4;
}
.msg-sub-title {
margin-left: 38px;
margin-top: 8px;
color: rgba(0,0,0,.65);
font-size: 14px;
}
}
</style>
挂载全局
创建一个index.js文件
// 导入confirmModal的vue文件
import confirmBox from './index'
const confirmModal = {
install: function(Vue) {
// 组件注册
const Msg = Vue.extend(confirmBox)
const msg = new Msg()
// 挂载
// 此处展示了两个盒子,是因为vue.extend方法挂载会覆盖原有的dom元素,销毁后便无法再次挂载
document.body.innerHTML += '<div id="confirmBox"><div id="confirmBox"></div></div>'
msg.$mount('#confirmBox')
// 全局注册
Vue.prototype.$msgBoxInfo = function(options) {
// 打开弹窗触发的方法
msg.open(options)
// 弹窗关闭后销毁组件,此处注销了,控制台会报错,但不影响功能
// msg.remove = function() {
// const msgDom = document.getElementById('confirmBox')
// document.body.removeChild(msgDom)
// msg.$destroy()
// }
return msg
}
}
}
export default confirmModal
最后在main.js中引用
import confirmModal from './components/ConfirmModal/ConfirmModal.js' //根据实际路径来
Vue.use(confirmModal)
调用方式
this.$msgBoxInfo({
title: '删除',
content: '确认删除此数据吗?',
onOk: () => {
console.log('点击确定')
},
onCancle: () => {
console.log('点击取消')
}
})