上一篇介绍了下个人对于简化表单的封装思路,仁者见仁智者见智吧,有些人觉得不错,有的人觉得画蛇添足,但总归来说,并不是毫无用处不是吗?
对于想要快速或者或则接外包的同学来说,我觉得应该还是用得上的,所以现在来讲讲怎么快速构建一个CRUD的界面。
按正常来说一个后台界面包含增删改查至少需要一个顶部菜单栏、查询表单、Table列表分页、弹窗编辑页
熟练的同学可能有代码生成器生成下一大堆代码就上去了,那我们现在主要讲的不是代码生成器这玩意哈,功能确定下来,现在上代码瞅一瞅:
<script lang="ts" setup>
import { ElsMessage } from 'element-less';
import { ElMessageBox } from 'element-plus';
const tableRef = ref()
const formRef = ref()
const editData = ref()
const dialogTitle = ref()
const dialogVisible = ref()
const containerRef = ref()
const editTemplate = {
id: 0,
name: '',
code: '',
config: [],
value: [],
isRelease: 0,
desc: ''
}
const toolData = ref([
{
"name": "查询",
"color": "primary",
"icon": "search",
"action": 'Search',
},
{
"name": "新增配置",
"color": "primary",
"icon": "edit",
"action": () => {
dialogTitle.value = '新增配置'
editData.value = editTemplate
dialogVisible.value = true
return Promise.resolve(true)
},
}])
function handleSave() {
return new Promise((resolve, reject) => {
formRef.value.validate().then((valid: boolean) => {
if (!valid) {
resolve(false)
} else {
formRef.value.save().then((res: any) => {
tableRef.value.searchData()
resolve(res)
})
}
})
})
}
function handleEdit(row: any) {
dialogTitle.value = '修改配置'
editData.value = row
dialogVisible.value = true
}
function handleDelete(row: any) {
ElMessageBox.confirm('确认删除?')
.then(() => {
`/admin/cm/config/delete?id=${row.id}`.get().then(res => {
tableRef.value.searchData()
ElsMessage.success('删除成功')
})
})
}
</script>
<template>
<ElsContainer ref="containerRef">
<ElsFormQuery>
<ElsInput prop="code" placeholder="请输入配置编码"></ElsInput>
<ElsMenuTool :data="toolData" text bg></ElsMenuTool>
</ElsFormQuery>
<ElsTable url="/admin/cm/config/list" ref="tableRef">
<ElsColumn prop="id" label="ID" sortable width="100"></ElsColumn>
<ElsColumn prop="name" label="名称" width="200"></ElsColumn>
<ElsColumn prop="code" label="配置编码" width="200"></ElsColumn>
<ElsColumn prop="desc" label="说明"></ElsColumn>
<ElsColumnBool prop="isRelease" label="是否启用" width="100"></ElsColumnBool>
<ElsColumn prop="createdAt" label="创建时间" width="200" dateFormatter="YYYY-MM-DD HH:mm:ss"></ElsColumn>
<ElsColumn label="操作" width="200">
<template #default="{ row }">
<el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
<el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
</template>
</ElsColumn>
</ElsTable>
<ElsDialog v-model="dialogVisible" :title="dialogTitle" :confirm="handleSave">
<ElsForm v-model="editData" ref="formRef" saveUrl="/admin/cm/config/save">
<ElsSwitch label="是否发布" prop="isRelease"></ElsSwitch>
<ElsInput label="名称" prop="name" required></ElsInput>
<ElsInput label="配置编码" prop="code" required></ElsInput>
<ElsTextarea label="说明" prop="desc"></ElsTextarea>
</ElsForm>
</ElsDialog>
</ElsContainer>
</template>
这段封装的代码中我将查询、新增、编辑功能都已经在各自的组件中,在ElsMenuTool中添加了顶部菜单的处理、ElsTable中添加了url用做接口请求该组件也已经包含分页、状态保持、EslDialog中添加confirm和saveUrl保存表单。
如果有什么哪里需要改进或则优化的地方欢迎各位看官吐槽哈