Vue自定义弹窗确认组件 — confirm
由于element-ui的弹窗确认组件是封装在message-box中,alert
、confirm
、prompt
统一封装在一起的,那么如果只封装confirm
组件要怎么做呢?
效果图
话不多说,直接上主干代码!如需了解组件库的边写步骤,请点击前往 Vue组件库开发>>
在 main.js
中
javascript
import Vue from 'vue';
import Main from './main.vue';
let ConfirmBox = Vue.extend(Main);
// 全局注册组件
Confirm= (content, title, options) => {
if (typeof title === 'object') {
options = title;
title = '';
} else if (title === undefined) {
title = '';
}
options = Object.assign({
title: title,
content: content
}, options);
let instance = new ConfirmBox({
data: options
}).$mount();
document.body.appendChild(instance.$el);
return instance.confirm();
}
export default Confirm;
在 main.vue
中
vue
<template>
<transition name="fade">
<div class="confirm-wrap"
v-if="visible"
@cllck="closeOnClickModal && close()">
<div class="confirm">
<div class="confirm-close"
v-if="showClose"
@click="close">
</div>
<div class="confirm-title" v-show="title">{{ title }}</div>
<div class="confirm-content">
{{ content }}
</div>
<div class="confirm-btn">
<button v-if="shwoCancelButton"
:button-name="cancelButtonText"
:button-type="curCancelButtonType"
@click="close">
</button>
<button v-if="shwoConfirmButton"
:button-name="ConfirmButtonText"
:button-type="curConfirmButtonType"
@click="close('confirm')">
</button>
</div>
</div>
</div>
</transition>
</template>
<script>
export default {
name: 'Confirm',
data () {
return {
visible: false,
confirmButtonType: '',
cancelButtonType: '',
confirmButtonText: '确定',
cancelButtonText: '取消',
showCancelButton: true,
content: '',
title: '',
showClose: true,
showConfirmButton: true,
closeOnClickModal: false
}
},
computed: {
curConfirmButtonType () {
return this.confirmButtonType ? this.confirmButtonType : 'normal'
},
curCancelButtonType () {
return this.cancelButtonType ? this.cancelButtonType : 'cancel'
}
},
methods: {
confirm () {
this.visible = true;
return new Promise((resolve, reject) => {
this.promiseStatus = { resolve, reject };
})
},
close (val) {
this.visible = false;
if (val == 'confirm') {
this.promiseStatus && this.promiseStatus.resolve();
} else {
this.promiseStatus && this.promiseStatus.reject();
}
}
}
}
</script>
调用方法:
javascript
this.$Confirm('删除后不可恢复,确定删除此文件?',‘提示’,{
confirmButtonText: '删除',
cancelButtonText: '取消'
}).then(() => {
// 成功
}).catch(err => {
// 失败
})
参数 | 说明 | 类型 | 可选值 | 默认值 |
---|---|---|---|---|
title | 标题 | String | - | - |
content | 正文内容 | String | - | - |
showClose | 是否显示右上角关闭按钮 | Boolean | - | true |
showCancelButton | 是否显示取消按钮 | Boolean | - | true |
showConfirmButton | 是否显示确定按钮 | Boolea n | - | true |
cancelButtonText | 取消按钮的文本内容 | String | - | 取消 |
confirmButtonText | 确定按钮的文本内容 | String | - | 确定 |
closeOnClickModal | 是否可通过点击遮罩关闭 | Boolean | - | false |