likes
comments
collection
share

useTable表格hooks封装和使用(Vue3)

作者站长头像
站长
· 阅读数 23

表格是中后台频繁使用的组件,vue3提供了hooks写法能够大大减少代码量和提高复用性,以下是一个基于arco design vue组件库封装的表格hooks:useTable

这个hooks相比于其他表格hooks的优点:

  • apiapi 参数 不分离,不会破坏原有的接口api
  • api参数 能够在外面进行过滤
  • 分页参数 pagin: { page, size } 能够按需使用

usePagination 的封装

useTable表格hooks封装和使用(Vue3)

useTable 的封装

useTable表格hooks封装和使用(Vue3)

文档

api参数

名称说明
api(pagin)表格数据接口api,pagin: {page, size}

options参数

参数说明
formatResult结果数据集过滤
onSuccess数据请求成功回调
immediate是否立即触发请求(默认true)
rowKey表格的数据rowKey

useTable 的使用

useTable表格hooks封装和使用(Vue3)

源码

import type { TableInstance } from '@arco-design/web-vue'
import { usePagination } from '@/hooks'

interface Options<T> {
  formatResult?: (data: T[]) => any
  onSuccess?: () => void
  immediate?: boolean
  rowKey?: keyof T
}

type PaginationParams = { page: number; size: number }
type Api<T> = (params: PaginationParams) => Promise<ApiRes<ApiListData<T[]>>>

export default function <T>(api: Api<T>, options?: Options<T>) {
  const { formatResult, onSuccess, immediate, rowKey } = options || {}
  const { pagination, setTotal } = usePagination(() => getTableData())
  const loading = ref(false)
  const tableData = ref<T[]>([])

  const getTableData = async () => {
    try {
      loading.value = true
      const res = await api({ page: pagination.current, size: pagination.pageSize })
      tableData.value = formatResult ? formatResult(res.data.list) : res.data.list
      setTotal(res.data.total)
      onSuccess && onSuccess()
    } catch (error) {
    } finally {
      loading.value = false
    }
  }

  const isImmediate = immediate ?? true
  isImmediate && getTableData()

  // 多选
  const selectKeys = ref<(string | number)[]>([])
  const select: TableInstance['onSelect'] = (rowKeys) => {
    selectKeys.value = rowKeys
  }

  // 全选
  const selectAll: TableInstance['onSelectAll'] = (checked) => {
    const key = rowKey ?? ('id' as keyof T)
    selectKeys.value = checked ? tableData.value.map((i) => i[key] as string | number) : []
  }

  return { loading, tableData, getTableData, pagination, selectKeys, select, selectAll }
}

后续新增删除功能

useTable表格hooks封装和使用(Vue3)

useTable表格hooks封装和使用(Vue3)

演示效果

useTable表格hooks封装和使用(Vue3)

来源

如遇接口请求出错,请使用浏览器打开预览

Gi Admin Pro

其他文章

转载自:https://juejin.cn/post/7289661061984649275
评论
请登录