前言
开发后台管理系统时,经常需要使用对话框,封装成公共组件方便复用及管理
开始封装
以vue3+element-plus为例
在src/components
中新建diaLog.vue
文件,使用具名插槽,让父组件决定渲染的内容
<template>
<el-dialog
v-model="visible"
:width="width"
@close="close"
>
<template #title>
<slot name="title"></slot>
</template>
<slot name="content"></slot>
<template #footer>
<slot name="footer"></slot>
</template>
</el-dialog>
</template>
<script>
import { reactive, toRefs, watch } from 'vue'
export default {
name: 'DiaLog',
props: {
dialogVisible: {
type: Boolean,
default: () => false
},
width: {
type: String,
default: '30%'
}
},
setup(props, { emit }) {
const state = reactive({
visible: false,
width: props.width
})
const bindfn = {
close() {
emit('closeDiaLog')
}
}
watch(() => props.dialogVisible,
(val) => {
state.visible = val
}
)
return {
...toRefs(state),
...bindfn
}
}
}
</script>
父组件使用dialog
<template>
<el-button @click="openDiaLog">dialog</el-button>
<DiaLog :dialogVisible="dialogVisible" @closeDiaLog="closeDiaLog" :width="'30%'">
<template #title>
<div>
<i class="el-icon-info"></i>
自定义标题
</div>
</template>
<template #content>
<p>something</p>
</template>
<template #footer>
<el-button @click="confirm">确定</el-button>
</template>
</DiaLog>
</template>
<script>
import { reactive, toRefs } from 'vue'
import DiaLog from './diaLog.vue'
import { ElMessage } from 'element-plus'
export default {
name: 'HelloWorld',
components: {
DiaLog
},
setup() {
const state = reactive({
dialogVisible: false,
})
const bindfn = {
openDiaLog() {
state.dialogVisible = true;
},
closeDiaLog() {
state.dialogVisible = false;
},
confirm() {
// 对话框确认后要执行的操作
ElMessage.success('成功')
state.dialogVisible = false;
}
}
return {
...toRefs(state),
...bindfn
}
}
}
</script>
效果图
传入表格