基于antd+vue3的分页逻辑抽象化
在后台管理系统中,分页样式以及逻辑一致,容易出现的问题的地方重复,所以分页逻辑进行封装, 这样当我们遇到相同问题的时候,只需要维护一套代码就可以解决问题
设计思想
1.需要赋值调用接口函数
2.需要赋值自定义排序函数
抽象逻辑
import { computed, reactive, ref } from 'vue'
export default function usePagination(initDatas) {
// 分页数量
const pageCoid = reactive({
current: 1,
pageSize: 10,
total: 0
})
// 请求loading效果
const loading = ref(false)
// 其他请求参数
const searchOther = ref({})
// 请求接口的数据
const searchCoild = computed(() => {
return {
...searchOther.value,
page: pageCoid.current,
pageSize: pageCoid.pageSize
}
})
// 接口名称
const postname = ref(null)
// 接口返回值
const returnValue = ref([])
// 请求接口
function getData() {
loading.value = true
postname.value(searchCoild.value).then((res) => {
returnValue.value = res.data
pageCoid.total = Number(res.data.total)
loading.value = false
})
}
// 分页数据
const pagination = computed(() => {
return {
total: pageCoid.total,
showSizeChanger: true,
showQuickJumper: true,
pageSize: pageCoid.pageSize,
current: pageCoid.current, // 页面
showTotal: (total, range) => `共 ${Math.ceil(pageCoid.total / pageCoid.pageSize)} 页 / ${total} 条数据`
}
})
// 表格自定义排序筛选
const pagesortfun = ref()
// 普通分页
const pageChange = (current, pageSize) => {
pageCoid.current = current
pageCoid.pageSize = pageSize
getData.value(searchCoild.value)
}
// 表格分页
const pageTabChange = (pag, filters, sorter) => {
pageCoid.current = pag.current
pageCoid.pageSize = pag.pageSize
pagesortfun.value(pag, filters, sorter)
getData.value(searchCoild.value)
}
const selectedIds = ref([])
// 选框
const rowSelection = {
columnWidth: 40,
onChange: (selectedRowKeys, selectedRows) => {
const selectValue = []
selectedRows.forEach((item) => {
selectValue.push(item.id)
})
selectedIds.value = selectValue
}
}
return {
loading, // loading效果
searchOther, // 其他搜索条件
searchCoild, // 全部搜索条件
pageCoid, // 当前页数,页码
pagination, // 分页配置
postname, // 接口名称
returnValue, // 表格数据
getData, // 请求接口
pagesortfun, // 表格自定义函数
pageChange, // 普通分页改变页码,页数方法
pageTabChange, // 表格改变页码,页数方法
selectedIds, // 选中数组id
rowSelection // 复选框配置
}
}
逻辑使用
抽象逻辑引用
const {
loading, // loading效果
searchOther, // 其他搜索条件()
searchCoild, // 全部搜索条件
pageCoid, // 当前页数,页码
pagination, // 分页配置
postname, // 接口名称
tableData, // 表格数据
getData, // 请求接口
pagesortfun, // 表格自定义函数
// pageChange, // 普通分页改变页码,页数方法
pageTabChange // 表格改变页码,页数方法
// selectedIds, // 选中数组id
// rowSelection // 复选框配置
} = usePagination()
// mgrList 接口函数
// tableChange 自定义搜素函数
onMounted(() => {
postname.value = mgrList
pagesortfun.value = tableChange
getData(searchCoild.value)
})
// 分页
searchOther.value = {
addTimeSort: 0
}
const tableChange = (pag, filters, sorter) => {
if (sorter.order === 'ascend') {
searchOther.value.addTimeSort = 0
} else if (sorter.order === 'descend') {
searchOther.value.addTimeSort = 1
} else {
searchOther.value.addTimeSort = ''
}
}