<template>
<el-dialog v-model="dialogVisible" :title="title" :width="width"
:destroy-on-close="destroyOnClose"
:draggable="true" :close-on-click-modal="false"
:close-on-press-escape="false"
>
<!-- 插槽 -->
<slot></slot>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submit">
{{ confirmText }}
</el-button>
</span>
</template>
</el-dialog>
</template>
<script setup>
import { ref } from 'vue'
const dialogVisible = ref(false)
// 打开
const open = () => dialogVisible.value = true
// 关闭
const close = () => dialogVisible.value = false
const props = defineProps({
title: String, // 字段类型
width: {
type: String,
default: '40%' // 默认值
},
destroyOnClose: {
type: Boolean,
default: false
},
confirmText: {
type: String,
default: '提交'
}
})
const emit = defineEmits(['submit'])
const submit = () => emit('submit')
// 暴露给父组件
defineExpose({
open,
close,
submit
})
</script>
使用
显示和关闭模态框
先设置一个 Ref 来引用该组件:
<FormDialog ref="formDialogRef" title="添加商品" destroyOnClose @submit="onSubmit" >
...
</FormDialog>
之后可以在合适的地方通过调用 $ref.formDialogRef.open()
和 $ref.formDialogRef.close()
来实现模态框的打开和关闭。
<el-button type="primary" @click="addCategoryBtnClick"/>
addCategoryBtnClick () {
this.$refs.formDialogRef.open()
},
配置提交处理
在上一小节中通过 @submit
来绑定到该组件暴露出来的submit方法,然后自己配置点击按钮后会进行的操作即可:
onSubmit() {
this.$refs.formRef.validate(async (valid) => {
if (valid) {
console.log(this.resultForm);
let result = await addGoods(this.resultForm);
if (result === true) {
this.$refs.formDialogRef.close();
await this.getTableData();
}
} else {
console.log('error submit!!');
return false;
}
});
}