封装分页查询
useTable.ts
interface UseTableConfig {
immediate?: boolean // 初始化时请求一次
fetchDataAction: () => Promise<{
list: any[]
total?: number
}>
}
export const useTable = (config: UseTableConfig): => {
const { immediate = true } = config
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dataList = ref<any[]>([])
watch(() => currentPage.value, () => {
methods.getList()
})
watch(() => pageSize.value, () => {
// 当页数不为 1 时,修改页数会导致多次调用 getList 方法
if(unref(currentPage === 1)) {
methods.getList()
}else {
currentPage.value = 1
methods.getList()
}
})
onMounted(() => {
if(immediate) methods.getList()
})
const methods = {
getList: async () => {
loading.value = true
try {
const res = await config?.fetchDataAction
if(res) {
dataList.value = res.list
total.value = res.total || 0
}
}catch(error) {}
finally {
loading.value = false
}
}
}
return {
tableMethods: methods,
tableState: {
currentPage,
pageSize,
total,
dataList,
loading
}
}
}
在组件中使用
<script setup lang="ts">
const ids = ref<string[]>([])
const { tableState ,tableMethods } = useTable({
fetchDataAction: async () => {
const { currentPage, pageSize } = tableState
const res = await api({
page: unref(currentPage),
pageSize: unref(pageSize),
...unref(searchParams)
})
return {
list: res.data,
total: res.total
}
}
})
const { loading, dataList, total, currentPage, pageSize} = tableState
const { getList } = tableMethods
</script>
<template>
<el-table
v-model:pageSize="pageSize"
v-model:currentPage="currentPage"
:data="dataList"
:loading="loading"
:pagination="{total: total}"
/>
</template>
其他
修改组件css变量值
在src里的某处新建index.less文件,修改元素边框圆角、去掉加粗
:root {
.el-button, .el-select__wrapper {
--el-border-radius-base: 2px;
}
.el-button {
--el-button-font-weight: normal;
}
}
然后在入口文件里引入这个index.less文件就可以了