perf: 代码优化 views/table

This commit is contained in:
pany 2023-06-20 09:13:47 +08:00
parent d06985b8e6
commit d1c7480a4f
3 changed files with 63 additions and 88 deletions

View File

@ -7,6 +7,7 @@ import { Search, Refresh, CirclePlus, Delete, Download, RefreshRight } from "@el
import { usePagination } from "@/hooks/usePagination" import { usePagination } from "@/hooks/usePagination"
defineOptions({ defineOptions({
//
name: "ElementPlus" name: "ElementPlus"
}) })
@ -25,29 +26,32 @@ const formRules: FormRules = reactive({
password: [{ required: true, trigger: "blur", message: "请输入密码" }] password: [{ required: true, trigger: "blur", message: "请输入密码" }]
}) })
const handleCreate = () => { const handleCreate = () => {
formRef.value?.validate((valid: boolean) => { formRef.value?.validate((valid: boolean, fields) => {
if (valid) { if (valid) {
if (currentUpdateId.value === undefined) { if (currentUpdateId.value === undefined) {
createTableDataApi({ createTableDataApi(formData)
username: formData.username, .then(() => {
password: formData.password ElMessage.success("新增成功")
}).then(() => { getTableData()
ElMessage.success("新增成功") })
dialogVisible.value = false .finally(() => {
getTableData() dialogVisible.value = false
}) })
} else { } else {
updateTableDataApi({ updateTableDataApi({
id: currentUpdateId.value, id: currentUpdateId.value,
username: formData.username username: formData.username
}).then(() => {
ElMessage.success("修改成功")
dialogVisible.value = false
getTableData()
}) })
.then(() => {
ElMessage.success("修改成功")
getTableData()
})
.finally(() => {
dialogVisible.value = false
})
} }
} else { } else {
return false console.error("表单校验不通过", fields)
} }
}) })
} }
@ -109,20 +113,11 @@ const getTableData = () => {
}) })
} }
const handleSearch = () => { const handleSearch = () => {
if (paginationData.currentPage === 1) { paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
getTableData()
}
paginationData.currentPage = 1
} }
const resetSearch = () => { const resetSearch = () => {
searchFormRef.value?.resetFields() searchFormRef.value?.resetFields()
if (paginationData.currentPage === 1) { handleSearch()
getTableData()
}
paginationData.currentPage = 1
}
const handleRefresh = () => {
getTableData()
} }
//#endregion //#endregion
@ -156,8 +151,8 @@ watch([() => paginationData.currentPage, () => paginationData.pageSize], getTabl
<el-tooltip content="下载"> <el-tooltip content="下载">
<el-button type="primary" :icon="Download" circle /> <el-button type="primary" :icon="Download" circle />
</el-tooltip> </el-tooltip>
<el-tooltip content="刷新表格"> <el-tooltip content="刷新当前页">
<el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" /> <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
</el-tooltip> </el-tooltip>
</div> </div>
</div> </div>

View File

@ -11,12 +11,11 @@ import {
type VxeModalInstance, type VxeModalInstance,
type VxeModalProps, type VxeModalProps,
type VxeFormInstance, type VxeFormInstance,
type VxeFormProps, type VxeFormProps
type VxeGridPropTypes,
type VxeFormDefines
} from "vxe-table" } from "vxe-table"
defineOptions({ defineOptions({
//
name: "VxeTable" name: "VxeTable"
}) })
@ -136,26 +135,22 @@ const xGridOpt: VxeGridProps = reactive({
total: "total" total: "total"
}, },
ajax: { ajax: {
query: ({ page, form }: VxeGridPropTypes.ProxyAjaxQueryParams) => { query: ({ page, form }) => {
xGridOpt.loading = true xGridOpt.loading = true
crudStore.clearTable() crudStore.clearTable()
return new Promise<any>((resolve: Function) => { return new Promise((resolve) => {
let total = 0 let total = 0
let result: RowMeta[] = [] let result: RowMeta[] = []
/** 加载数据 */ /** 加载数据 */
const callback = (res: GetTableResponseData) => { const callback = (res: GetTableResponseData) => {
if (res && res.data) { if (res?.data) {
const resData = res.data
// //
if (Number.isInteger(resData.total)) { total = res.data.total
total = resData.total //
} result = res.data.list
//
if (Array.isArray(resData.list)) {
result = resData.list
}
} }
xGridOpt.loading = false xGridOpt.loading = false
// vxe-table
resolve({ total, result }) resolve({ total, result })
} }
@ -191,7 +186,7 @@ const xModalOpt: VxeModalProps = reactive({
//#region vxe-form //#region vxe-form
const xFormDom = ref<VxeFormInstance>() const xFormDom = ref<VxeFormInstance>()
const xFormOpt = reactive<VxeFormProps>({ const xFormOpt: VxeFormProps = reactive({
span: 24, span: 24,
titleWidth: "100px", titleWidth: "100px",
loading: false, loading: false,
@ -234,11 +229,11 @@ const xFormOpt = reactive<VxeFormProps>({
{ {
required: true, required: true,
validator: ({ itemValue }) => { validator: ({ itemValue }) => {
if (!itemValue) { switch (true) {
return new Error("请输入") case !itemValue:
} return new Error("请输入")
if (!itemValue.trim()) { case !itemValue.trim():
return new Error("空格无效") return new Error("空格无效")
} }
} }
} }
@ -247,11 +242,11 @@ const xFormOpt = reactive<VxeFormProps>({
{ {
required: true, required: true,
validator: ({ itemValue }) => { validator: ({ itemValue }) => {
if (!itemValue) { switch (true) {
return new Error("请输入") case !itemValue:
} return new Error("请输入")
if (!itemValue.trim()) { case !itemValue.trim():
return new Error("空格无效") return new Error("空格无效")
} }
} }
} }
@ -260,9 +255,9 @@ const xFormOpt = reactive<VxeFormProps>({
}) })
//#endregion //#endregion
//#region CRUD //#region
const crudStore = reactive({ const crudStore = reactive({
/** 表单类型修改true 新增false */ /** 表单类型true 表示修改false 表示新增 */
isUpdate: true, isUpdate: true,
/** 加载表格数据 */ /** 加载表格数据 */
commitQuery: () => xGridDom.value?.commitProxy("query"), commitQuery: () => xGridDom.value?.commitProxy("query"),
@ -280,11 +275,8 @@ const crudStore = reactive({
xModalOpt.title = "新增用户" xModalOpt.title = "新增用户"
} }
// //
if (xFormOpt.items) { const props = xFormOpt.items?.[0]?.itemRender?.props
if (xFormOpt.items[0]?.itemRender?.props) { props && (props.disabled = crudStore.isUpdate)
xFormOpt.items[0].itemRender.props.disabled = crudStore.isUpdate
}
}
xModalDom.value?.open() xModalDom.value?.open()
nextTick(() => { nextTick(() => {
!crudStore.isUpdate && xFormDom.value?.reset() !crudStore.isUpdate && xFormDom.value?.reset()
@ -294,39 +286,38 @@ const crudStore = reactive({
/** 确定并保存 */ /** 确定并保存 */
onSubmitForm: () => { onSubmitForm: () => {
if (xFormOpt.loading) return if (xFormOpt.loading) return
xFormDom.value?.validate((errMap?: VxeFormDefines.ValidateErrorMapParams) => { xFormDom.value?.validate((errMap) => {
if (errMap) return if (errMap) return
xFormOpt.loading = true xFormOpt.loading = true
const callback = (err?: any) => { const callback = () => {
xFormOpt.loading = false xFormOpt.loading = false
if (err) return
xModalDom.value?.close() xModalDom.value?.close()
ElMessage.success("操作成功") ElMessage.success("操作成功")
!crudStore.isUpdate && crudStore.afterInsert() !crudStore.isUpdate && crudStore.afterInsert()
crudStore.commitQuery() crudStore.commitQuery()
} }
if (crudStore.isUpdate) { if (crudStore.isUpdate) {
// //
setTimeout(() => callback(), 1000) setTimeout(() => callback(), 1000)
} else { } else {
// //
setTimeout(() => callback(), 1000) setTimeout(() => callback(), 1000)
} }
}) })
}, },
/** 新增后是否跳入最后一页 */ /** 新增后是否跳入最后一页 */
afterInsert: () => { afterInsert: () => {
const pager: VxeGridPropTypes.ProxyAjaxQueryPageParams | undefined = xGridDom.value?.getProxyInfo()?.pager const pager = xGridDom.value?.getProxyInfo()?.pager
if (pager) { if (pager) {
const currTotal: number = pager.currentPage * pager.pageSize const currentTotal = pager.currentPage * pager.pageSize
if (currTotal === pager.total) { if (currentTotal === pager.total) {
++pager.currentPage ++pager.currentPage
} }
} }
}, },
/** 删除 */ /** 删除 */
onDelete: (row: RowMeta) => { onDelete: (row: RowMeta) => {
const tip = `确定 <strong style='color:red;'>删除</strong> 用户 <strong style='color:#409eff;'>${row.username}</strong> ` const tip = `确定 <strong style="color: red"> 删除 </strong> 用户 <strong style="color: #409eff"> ${row.username} </strong> `
const config: ElMessageBoxOptions = { const config: ElMessageBoxOptions = {
type: "warning", type: "warning",
showClose: true, showClose: true,
@ -336,28 +327,24 @@ const crudStore = reactive({
confirmButtonText: "确定", confirmButtonText: "确定",
dangerouslyUseHTMLString: true dangerouslyUseHTMLString: true
} }
ElMessageBox.confirm(tip, "提示", config) ElMessageBox.confirm(tip, "提示", config).then(() => {
.then(() => { deleteTableDataApi(row.id).then(() => {
deleteTableDataApi(row.id) ElMessage.success("删除成功")
.then(() => { crudStore.afterDelete()
ElMessage.success("删除成功") crudStore.commitQuery()
crudStore.afterDelete()
crudStore.commitQuery()
})
.catch(() => 1)
}) })
.catch(() => 1) })
}, },
/** 删除后是否返回上一页 */ /** 删除后是否返回上一页 */
afterDelete: () => { afterDelete: () => {
const tableData: RowMeta[] = xGridDom.value!.getData() const tableData: RowMeta[] = xGridDom.value!.getData()
const pager: VxeGridPropTypes.ProxyAjaxQueryPageParams | undefined = xGridDom.value?.getProxyInfo()?.pager const pager = xGridDom.value?.getProxyInfo()?.pager
if (pager && pager.currentPage > 1 && tableData.length === 1) { if (pager && pager.currentPage > 1 && tableData.length === 1) {
--pager.currentPage --pager.currentPage
} }
}, },
/** 更多自定义方法 */ /** 更多自定义方法 */
moreFunc: () => {} moreFn: () => {}
}) })
//#endregion //#endregion
</script> </script>
@ -384,5 +371,3 @@ const crudStore = reactive({
</vxe-modal> </vxe-modal>
</div> </div>
</template> </template>
<style lang="scss" scoped></style>

View File

@ -3,12 +3,7 @@ import { type VxeColumnPropTypes } from "vxe-table/types/column"
const solts: VxeColumnPropTypes.Slots = { const solts: VxeColumnPropTypes.Slots = {
default: ({ row, column }) => { default: ({ row, column }) => {
const cellValue = row[column.field] const cellValue = row[column.field]
let type = "danger" const [type, value] = cellValue ? ["success", "启用"] : ["danger", "禁用"]
let value = "禁用"
if (cellValue) {
type = "success"
value = "启用"
}
return [<span class={`el-tag el-tag--${type} el-tag--plain`}>{value}</span>] return [<span class={`el-tag el-tag--${type} el-tag--plain`}>{value}</span>]
} }
} }