一、弹框组件BaseDialog
<template><div class='main'><el-dialog v-model="visible" :title="title" :width="dialogWidth" :before-close="handleClose"><!-- 内容插槽 --><slot></slot><template #footer><span class="dialog-footer"><el-button v-if="showCancelButton" @click="handleClose">取消</el-button><el-button v-if="showConfirmButton" type="primary" @click="handleConfirm">确认</el-button></span></template></el-dialog></div>
</template><script lang='ts' setup>
import { ElMessageBox } from 'element-plus'
import { ref, reactive, getCurrentInstance, onMounted, defineExpose, defineEmits } from 'vue'
/*** 传入的props变量
*/
const props = defineProps({title: {type: String,default: '提示',},dialogWidth: {type: String,default: '40%',},showCancelButton: {type: Boolean,default: true,},showConfirmButton: {type: Boolean,default: true,},})
/*** 发射给父组件的方法 * 用于子组件给父组件传值或调用父组件方法
*/
const emits = defineEmits(['submit', 'close'])
const visible = ref(false)
// 关闭弹框
const handleClose = () => {emits('close')
}
// 打开弹框
const handleOpen = () => {visible.value = true
}
// 确认事件
const handleConfirm = () => {emits('submit')
}
/*** 暴露给父组件的方法* 用于父组件调用子组件方法或获取子组件属性值
*/
defineExpose({ handleOpen, handleClose, visible })
onMounted(() => {
})</script>
<style scoped lang='scss'>
</style>
二、在index.vue中使用
<el-button @click="showDialog">点击出现弹框</el-button><BaseDialog ref="baseDialog" @submit="handleSubmit" @close="handleClose"><div><el-input placeholder="Please input" /></div></BaseDialog>
<script lang='ts' setup>
import BaseDialog from '@/components/BaseDialog/index.vue'
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
onMounted(() => {
})
// 获取子组件的ref
let baseDialog = ref()
// 点击出现弹框
const showDialog = () => {// 调用子组件方法,打开弹框baseDialog.value.handleOpen()
}
// 弹框确认事件
const handleSubmit = () => {console.log('我是父组件中的确认事件')
}
// 弹框取消事件
const handleClose = () => {baseDialog.value.visible = false
}
</script>
三、效果