封装组件:
// 对话框组件
<template>
<el-dialog
v-model="isShow"
:title="title"
:width="width"
@open="onOpen"
@close="onClose"
>
...
<!-- 操作按钮 -->
<template #footer>
<div class="footerBtn">
<el-button @click="onClose">取消</el-button>
<el-button type="primary" :loading="loading" @click="onSubmit">确定</el-button>
</div>
</template>
</el-dialog>
</template>
<script setup>
import { ref, computed } from "vue"
import { ElMessage } from 'element-plus'
const props = defineProps({
visible: {
type: Boolean,
required: true,
default: false
},
title: {
type: String,
default: ''
},
width: {
type: String,
default: '50%'
},
})
const emits = defineEmits(['update:visible','onUpdate']);
// 对话框显隐
const isShow = computed({
get() {
return props.visible;
},
set(val) {
emits("update:visible", val);
}
})
// 打开弹窗时获取数据
const onOpen = () => {
// 请求数据
...
}
// 提交/确认
const loading = ref(false);
const onSubmit = () => {
loading.value = true;
// 提交接口
Api(...).then(res => {
ElMessage({
message: `操作成功!`,
type: 'success',
})
emits("onUpdate");
onClose();
}).finally(() => {
loading.value = false;
})
}
//取消/关闭
const onClose = () => {
isShow.value = false;
//其他清空操作
...
}
</script>
<style lang="scss" scoped>
.footerBtn {
display: flex;
align-items: center;
justify-content: center;
button {
margin-right: 20px;
&:last-of-type {
margin-right: 0;
}
}
}
</style>
父组件调用:
<CustomDialog :visible="visible" @update:visible="visible = $event" @onUpdate="onUpdate" />