index.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <template>
  2. <!-- 查询表单 -->
  3. <SearchForm v-show="isShowSearch" :search="_search" :reset="_reset" :columns="searchColumns" :search-param="searchParam" :search-col="searchCol" />
  4. <!-- 表格主体 -->
  5. <div class="card table-main">
  6. <!-- 表格头部 操作按钮 -->
  7. <div class="table-header">
  8. <div class="header-button-lf">
  9. <slot name="tableHeader" :selected-list="selectedList" :selected-list-ids="selectedListIds" :is-selected="isSelected" />
  10. </div>
  11. <div v-if="toolButton" class="header-button-ri">
  12. <slot name="toolButton">
  13. <el-button v-if="showToolButton('refresh')" icon="Refresh" circle @click="getTableList" />
  14. <el-button v-if="showToolButton('setting') && columns.length" icon="Operation" circle @click="openColSetting" />
  15. <el-button v-if="showToolButton('search') && searchColumns?.length" icon="Search" circle @click="isShowSearch = !isShowSearch" />
  16. </slot>
  17. </div>
  18. </div>
  19. <!-- 表格主体 -->
  20. <el-table ref="tableRef" v-bind="$attrs" :data="processTableData" :border="border" :row-key="rowKey" @selection-change="selectionChange">
  21. <!-- 默认插槽 -->
  22. <slot />
  23. <template v-for="item in tableColumns" :key="item">
  24. <!-- selection || radio || index || expand || sort -->
  25. <el-table-column
  26. v-if="item.type && columnTypes.includes(item.type)"
  27. v-bind="item"
  28. :align="item.align ?? 'center'"
  29. :reserve-selection="item.type == 'selection'"
  30. >
  31. <template #default="scope">
  32. <!-- expand -->
  33. <template v-if="item.type == 'expand'">
  34. <component :is="item.render" v-bind="scope" v-if="item.render" />
  35. <slot v-else :name="item.type" v-bind="scope" />
  36. </template>
  37. <!-- radio -->
  38. <el-radio v-if="item.type == 'radio'" v-model="radio" :label="scope.row[rowKey]">
  39. <i></i>
  40. </el-radio>
  41. <!-- sort -->
  42. <el-tag v-if="item.type == 'sort'" class="move">
  43. <el-icon> <DCaret /></el-icon>
  44. </el-tag>
  45. </template>
  46. </el-table-column>
  47. <!-- other -->
  48. <TableColumn v-if="!item.type && item.prop && item.isShow" :column="item">
  49. <template v-for="slot in Object.keys($slots)" #[slot]="scope">
  50. <slot :name="slot" v-bind="scope" />
  51. </template>
  52. </TableColumn>
  53. </template>
  54. <!-- 插入表格最后一行之后的插槽 -->
  55. <template #append>
  56. <slot name="append" />
  57. </template>
  58. <!-- 无数据 -->
  59. <template #empty>
  60. <div class="table-empty">
  61. <slot name="empty">
  62. <img src="@/assets/images/notData.png" alt="notData" />
  63. <div>暂无数据</div>
  64. </slot>
  65. </div>
  66. </template>
  67. </el-table>
  68. <!-- 分页组件 -->
  69. <slot name="pagination">
  70. <Pagination v-if="pagination" :pageable="pageable" :handle-size-change="handleSizeChange" :handle-current-change="handleCurrentChange" />
  71. </slot>
  72. </div>
  73. <!-- 列设置 -->
  74. <ColSetting v-if="toolButton" ref="colRef" v-model:col-setting="colSetting" />
  75. </template>
  76. <script setup lang="ts" name="ProTable">
  77. import { ref, watch, provide, onMounted, unref, computed, reactive } from 'vue'
  78. import { ElTable } from 'element-plus'
  79. import { useTable } from '@/hooks/useTable'
  80. import { useSelection } from '@/hooks/useSelection'
  81. import { BreakPoint } from '@/components/Grid/interface'
  82. import { ColumnProps, TypeProps } from '@/components/ProTable/interface'
  83. import { handleProp } from '@/utils'
  84. import SearchForm from '@/components/SearchForm/index.vue'
  85. import Pagination from './components/Pagination.vue'
  86. import ColSetting from './components/ColSetting.vue'
  87. import TableColumn from './components/TableColumn.vue'
  88. import Sortable from 'sortablejs'
  89. export interface ProTableProps {
  90. columns: ColumnProps[] // 列配置项 ==> 必传
  91. data?: any[] // 静态 table data 数据,若存在则不会使用 requestApi 返回的 data ==> 非必传
  92. requestApi?: (params: any) => Promise<any> // 请求表格数据的 api ==> 非必传
  93. requestAuto?: boolean // 是否自动执行请求 api ==> 非必传(默认为true)
  94. requestError?: (params: any) => void // 表格 api 请求错误监听 ==> 非必传
  95. dataCallback?: (data: any) => any // 返回数据的回调函数,可以对数据进行处理 ==> 非必传
  96. title?: string // 表格标题 ==> 非必传
  97. pagination?: boolean // 是否需要分页组件 ==> 非必传(默认为true)
  98. initParam?: any // 初始化请求参数 ==> 非必传(默认为{})
  99. border?: boolean // 是否带有纵向边框 ==> 非必传(默认为true)
  100. toolButton?: ('refresh' | 'setting' | 'search')[] | boolean // 是否显示表格功能按钮 ==> 非必传(默认为true)
  101. isShowSearch?: boolean
  102. rowKey?: string // 行数据的 Key,用来优化 Table 的渲染,当表格数据多选时,所指定的 id ==> 非必传(默认为 id)
  103. searchCol?: number | Record<BreakPoint, number> // 表格搜索项 每列占比配置 ==> 非必传 { xs: 1, sm: 2, md: 2, lg: 3, xl: 4 }
  104. }
  105. // 接受父组件参数,配置默认值
  106. const props = withDefaults(defineProps<ProTableProps>(), {
  107. columns: () => [],
  108. requestAuto: true,
  109. pagination: true,
  110. initParam: {},
  111. border: true,
  112. data: () => [],
  113. toolButton: true,
  114. isShowSearch: true,
  115. rowKey: 'id',
  116. searchCol: () => ({ xs: 1, sm: 2, md: 2, lg: 3, xl: 4 })
  117. })
  118. // table 实例
  119. const tableRef = ref<InstanceType<typeof ElTable>>()
  120. // column 列类型
  121. const columnTypes: TypeProps[] = ['selection', 'radio', 'index', 'expand', 'sort']
  122. // 是否显示搜索模块
  123. const isShowSearch = ref(props.isShowSearch)
  124. // 控制 ToolButton 显示
  125. const showToolButton = (key: 'refresh' | 'setting' | 'search') => {
  126. return Array.isArray(props.toolButton) ? props.toolButton.includes(key) : props.toolButton
  127. }
  128. // 单选值
  129. const radio = ref('')
  130. // 表格多选 Hooks
  131. const { selectionChange, selectedList, selectedListIds, isSelected } = useSelection(props.rowKey)
  132. // 表格操作 Hooks
  133. const { tableData, pageable, searchParam, searchInitParam, getTableList, search, reset, handleSizeChange, handleCurrentChange } = useTable(
  134. props.requestApi,
  135. props.initParam,
  136. props.pagination,
  137. props.dataCallback,
  138. props.requestError
  139. )
  140. // 清空选中数据列表
  141. const clearSelection = () => tableRef.value!.clearSelection()
  142. // 初始化表格数据 && 拖拽排序
  143. onMounted(() => {
  144. dragSort()
  145. props.requestAuto && getTableList()
  146. props.data && (pageable.value.total = props.data.length)
  147. })
  148. // 处理表格数据
  149. const processTableData = computed(() => {
  150. if (!props.data) return tableData.value
  151. if (!props.pagination) return props.data
  152. return props.data.slice((pageable.value.pageNum - 1) * pageable.value.pageSize, pageable.value.pageSize * pageable.value.pageNum)
  153. })
  154. // 监听页面 initParam 改化,重新获取表格数据
  155. watch(() => props.initParam, getTableList, { deep: true })
  156. // 接收 columns 并设置为响应式
  157. const tableColumns = reactive<ColumnProps[]>(props.columns)
  158. // 扁平化 columns
  159. const flatColumns = computed(() => flatColumnsFunc(tableColumns))
  160. // 定义 enumMap 存储 enum 值(避免异步请求无法格式化单元格内容 || 无法填充搜索下拉选择)
  161. const enumMap = ref(new Map<string, { [key: string]: any }[]>())
  162. const setEnumMap = async ({ prop, enum: enumValue }: ColumnProps) => {
  163. if (!enumValue) return
  164. // 如果当前 enumMap 存在相同的值 return
  165. if (enumMap.value.has(prop!) && (typeof enumValue === 'function' || enumMap.value.get(prop!) === enumValue)) return
  166. // 当前 enum 为静态数据,则直接存储到 enumMap
  167. if (typeof enumValue !== 'function') return enumMap.value.set(prop!, unref(enumValue!))
  168. // 为了防止接口执行慢,而存储慢,导致重复请求,所以预先存储为[],接口返回后再二次存储
  169. enumMap.value.set(prop!, [])
  170. // 当前 enum 为后台数据需要请求数据,则调用该请求接口,并存储到 enumMap
  171. const { data } = await enumValue()
  172. enumMap.value.set(prop!, data)
  173. }
  174. // 注入 enumMap
  175. provide('enumMap', enumMap)
  176. // 扁平化 columns 的方法
  177. const flatColumnsFunc = (columns: ColumnProps[], flatArr: ColumnProps[] = []) => {
  178. columns.forEach(async col => {
  179. if (col._children?.length) flatArr.push(...flatColumnsFunc(col._children))
  180. flatArr.push(col)
  181. // column 添加默认 isShow && isFilterEnum 属性值
  182. col.isShow = col.isShow ?? true
  183. col.isFilterEnum = col.isFilterEnum ?? true
  184. // 设置 enumMap
  185. await setEnumMap(col)
  186. })
  187. return flatArr.filter(item => !item._children?.length)
  188. }
  189. // 过滤需要搜索的配置项 && 排序
  190. const searchColumns = computed(() => {
  191. return flatColumns.value?.filter(item => item.search?.el || item.search?.render).sort((a, b) => a.search!.order! - b.search!.order!)
  192. })
  193. // 设置 搜索表单默认排序 && 搜索表单项的默认值
  194. searchColumns.value?.forEach((column, index) => {
  195. column.search!.order = column.search?.order ?? index + 2
  196. const key = column.search?.key ?? handleProp(column.prop!)
  197. const defaultValue = column.search?.defaultValue
  198. if (defaultValue !== undefined && defaultValue !== null) {
  199. searchInitParam.value[key] = defaultValue
  200. searchParam.value[key] = defaultValue
  201. }
  202. })
  203. // 列设置 ==> 需要过滤掉不需要设置的列
  204. const colRef = ref()
  205. const colSetting = tableColumns!.filter(item => {
  206. const { type, prop, isShow } = item
  207. return !columnTypes.includes(type!) && prop !== 'operation' && isShow
  208. })
  209. const openColSetting = () => colRef.value.openColSetting()
  210. // 定义 emit 事件
  211. const emit = defineEmits<{
  212. search: []
  213. reset: []
  214. dargSort: [{ newIndex?: number; oldIndex?: number }]
  215. }>()
  216. const _search = () => {
  217. search()
  218. emit('search')
  219. }
  220. const _reset = () => {
  221. reset()
  222. emit('reset')
  223. }
  224. // 拖拽排序
  225. const dragSort = () => {
  226. const tbody = document.querySelector('.el-table__body-wrapper tbody') as HTMLElement
  227. Sortable.create(tbody, {
  228. handle: '.move',
  229. animation: 300,
  230. onEnd({ newIndex, oldIndex }) {
  231. const [removedItem] = processTableData.value.splice(oldIndex!, 1)
  232. processTableData.value.splice(newIndex!, 0, removedItem)
  233. emit('dargSort', { newIndex, oldIndex })
  234. }
  235. })
  236. }
  237. // 暴露给父组件的参数和方法 (外部需要什么,都可以从这里暴露出去)
  238. defineExpose({
  239. element: tableRef,
  240. tableData: processTableData,
  241. radio,
  242. pageable,
  243. searchParam,
  244. searchInitParam,
  245. getTableList,
  246. search,
  247. reset,
  248. handleSizeChange,
  249. handleCurrentChange,
  250. clearSelection,
  251. enumMap,
  252. isSelected,
  253. selectedList,
  254. selectedListIds
  255. })
  256. </script>