index.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <template>
  2. <div class="table-container">
  3. <div class="table-header mb15">
  4. <div>
  5. <slot name="command"></slot>
  6. </div>
  7. <div v-loading="state.importLoading" class="table-footer-tool">
  8. <SvgIcon v-if="!config.hideRefresh" name="iconfont icon-shuaxin" :size="22" title="刷新" @click="onRefreshTable" />
  9. <el-dropdown v-if="!config.hideExport" trigger="click">
  10. <SvgIcon name="iconfont icon-yunxiazai_o" :size="22" title="导出" />
  11. <template #dropdown>
  12. <el-dropdown-menu>
  13. <el-dropdown-item @click="onImportTable">导出本页数据</el-dropdown-item>
  14. <el-dropdown-item @click="onImportTableAll">导出全部数据</el-dropdown-item>
  15. </el-dropdown-menu>
  16. </template>
  17. </el-dropdown>
  18. <SvgIcon v-if="!config.hidePrint" name="iconfont icon-dayin" :size="19" title="打印" @click="onPrintTable" />
  19. <el-popover v-if="!config.hideSet" placement="bottom-end" trigger="click" transition="el-zoom-in-top" popper-class="table-tool-popper"
  20. :width="300" :persistent="false" @show="onSetTable">
  21. <template #reference>
  22. <SvgIcon name="iconfont icon-quanjushezhi_o" :size="22" title="设置" />
  23. </template>
  24. <template #default>
  25. <div class="tool-box">
  26. <el-tooltip content="拖动进行排序" placement="top-start">
  27. <SvgIcon name="fa fa-question-circle-o" :size="17" class="ml11" color="#909399" />
  28. </el-tooltip>
  29. <el-checkbox v-model="state.checkListAll" :indeterminate="state.checkListIndeterminate"
  30. class="ml10 mr1" label="列显示" @change="onCheckAllChange" />
  31. <el-checkbox v-model="getConfig.isSerialNo" class="ml12 mr1" label="序号" />
  32. <el-checkbox v-if="getConfig.showSelection" v-model="getConfig.isSelection" class="ml12 mr1"
  33. label="多选" />
  34. </div>
  35. <el-scrollbar>
  36. <div ref="toolSetRef" class="tool-sortable">
  37. <div class="tool-sortable-item" v-for="v in columns" :key="v.prop"
  38. v-show="!v.hideCheck && !v.fixed" :data-key="v.prop">
  39. <i class="fa fa-arrows-alt handle cursor-pointer"></i>
  40. <el-checkbox v-model="v.isCheck" size="default" class="ml12 mr8" :label="v.label"
  41. @change="onCheckChange" />
  42. </div>
  43. </div>
  44. </el-scrollbar>
  45. </template>
  46. </el-popover>
  47. </div>
  48. </div>
  49. <el-table ref="tableRef" :data="state.data" :border="setBorder" :stripe="setStripe" v-bind="$attrs" row-key="id"
  50. default-expand-all style="width: 100%" v-loading="state.loading" :default-sort="defaultSort"
  51. @selection-change="onSelectionChange" @sort-change="sortChange">
  52. <el-table-column type="selection" :reserve-selection="true" :width="30"
  53. v-if="config.isSelection && config.showSelection" />
  54. <el-table-column type="index" label="序号" align="center" :width="60" v-if="config.isSerialNo" />
  55. <el-table-column v-for="(item, index) in setHeader" :key="index" v-bind="item">
  56. <!-- 自定义列插槽,插槽名为columns属性的prop -->
  57. <template #default="scope" v-if="(!item.children) && $slots[item.prop]">
  58. <slot :name="item.prop" v-bind="scope"></slot>
  59. </template>
  60. <template v-else-if="!item.children" v-slot="scope">
  61. <template v-if="item.type === 'image'">
  62. <el-image :style="{ width: `${item.width}px`, height: `${item.height}px` }"
  63. :src="scope.row[item.prop]" :zoom-rate="1.2" :preview-src-list="[scope.row[item.prop]]"
  64. preview-teleported fit="cover" />
  65. </template>
  66. <template v-else>
  67. {{ scope.row[item.prop] }}
  68. </template>
  69. </template>
  70. <el-table-column v-for="(childrenItem, childrenIndex) in item.children" :key="childrenIndex" v-bind="childrenItem">
  71. <!-- 自定义列插槽,插槽名为columns属性的prop -->
  72. <template #default="scope" v-if="$slots[childrenItem.prop]">
  73. <slot :name="childrenItem.prop" v-bind="scope"></slot>
  74. </template>
  75. <template v-else v-slot="scope">
  76. <template v-if="childrenItem.type === 'image'">
  77. <el-image :style="{ width: `${childrenItem.width}px`, height: `${childrenItem.height}px` }"
  78. :src="scope.row[childrenItem.prop]" :zoom-rate="1.2" :preview-src-list="[scope.row[childrenItem.prop]]"
  79. preview-teleported fit="cover" />
  80. </template>
  81. <template v-else>
  82. {{ scope.row[childrenItem.prop] }}
  83. </template>
  84. </template>
  85. </el-table-column>
  86. </el-table-column>
  87. <template #empty>
  88. <el-empty description="暂无数据" />
  89. </template>
  90. </el-table>
  91. <div v-if="!config.hidePagination && state.showPagination" class="table-footer mt15">
  92. <el-pagination v-model:current-page="state.page.page" v-model:page-size="state.page.pageSize" small
  93. :pager-count="5" :page-sizes="config.pageSizes" :total="state.total"
  94. layout="total, sizes, prev, pager, next, jumper" background @size-change="onHandleSizeChange"
  95. @current-change="onHandleCurrentChange">
  96. </el-pagination>
  97. </div>
  98. </div>
  99. </template>
  100. <script setup lang="ts" name="netxTable">
  101. import { reactive, computed, nextTick, ref, onMounted } from 'vue';
  102. import { ElMessage } from 'element-plus';
  103. import Sortable from 'sortablejs';
  104. import { storeToRefs } from 'pinia';
  105. import { useThemeConfig } from '/@/stores/themeConfig';
  106. import { exportExcel } from '/@/utils/exportExcel';
  107. // import '/@/theme/tableTool.scss';
  108. import printJs from 'print-js';
  109. // 定义父组件传过来的值
  110. const props = defineProps({
  111. // 获取数据的方法,由父组件传递
  112. getData: {
  113. type: Function,
  114. required: true,
  115. },
  116. // 列属性,和elementUI的Table-column 属性相同,附加属性:isCheck-是否默认勾选展示,hideCheck-是否隐藏该列的可勾选和拖拽
  117. columns: {
  118. type: Array<any>,
  119. default: () => [],
  120. },
  121. // 配置项:isBorder-是否显示表格边框,isSerialNo-是否显示表格序号,showSelection-是否显示表格可多选,isSelection-是否默认选中表格多选,pageSize-每页条数,hideExport-是否隐藏导出按钮,exportFileName-导出表格的文件名,空值默认用应用名称作为文件名
  122. config: {
  123. type: Object,
  124. default: () => { },
  125. },
  126. // 筛选参数
  127. param: {
  128. type: Object,
  129. default: () => { },
  130. },
  131. // 默认排序方式,{prop:"排序字段",order:"ascending or descending"}
  132. defaultSort: {
  133. type: Object,
  134. default: () => { },
  135. },
  136. // 导出报表自定义数据转换方法,不传按字段值导出
  137. exportChangeData: {
  138. type: Function,
  139. },
  140. // 打印标题
  141. printName: {
  142. type: String,
  143. default: () => '',
  144. },
  145. });
  146. // 定义子组件向父组件传值/事件,pageChange-翻页事件,selectionChange-表格多选事件,可以在父组件处理批量删除/修改等功能,sortHeader-拖拽列顺序事件
  147. const emit = defineEmits(['pageChange', 'selectionChange', 'sortHeader']);
  148. // 定义变量内容
  149. const toolSetRef = ref();
  150. const tableRef = ref();
  151. const storesThemeConfig = useThemeConfig();
  152. const { themeConfig } = storeToRefs(storesThemeConfig);
  153. const state = reactive({
  154. data: [] as Array<EmptyObjectType>,
  155. loading: false,
  156. importLoading: false,
  157. total: 0,
  158. page: {
  159. page: 1,
  160. pageSize: 10,
  161. field: '',
  162. order: '',
  163. },
  164. showPagination: true,
  165. selectlist: [] as EmptyObjectType[],
  166. checkListAll: true,
  167. checkListIndeterminate: false,
  168. });
  169. // 设置边框显示/隐藏
  170. const setBorder = computed(() => {
  171. return props.config.isBorder ? true : false;
  172. });
  173. // 设置斑马纹显示/隐藏
  174. const setStripe = computed(() => {
  175. return props.config.isStripe ? true : false;
  176. });
  177. // 获取父组件 配置项(必传)
  178. const getConfig = computed(() => {
  179. return props.config;
  180. });
  181. // 设置 tool header 数据
  182. const setHeader = computed(() => {
  183. return props.columns.filter((v) => v.isCheck);
  184. });
  185. // tool 列显示全选改变时
  186. const onCheckAllChange = <T>(val: T) => {
  187. if (val) props.columns.forEach((v) => (v.isCheck = true));
  188. else props.columns.forEach((v) => (v.isCheck = false));
  189. state.checkListIndeterminate = false;
  190. };
  191. // tool 列显示当前项改变时
  192. const onCheckChange = () => {
  193. const headers = props.columns.filter((v) => v.isCheck).length;
  194. state.checkListAll = headers === props.columns.length;
  195. state.checkListIndeterminate = headers > 0 && headers < props.columns.length;
  196. };
  197. // 表格多选改变时
  198. const onSelectionChange = (val: EmptyObjectType[]) => {
  199. state.selectlist = val;
  200. emit('selectionChange', state.selectlist);
  201. };
  202. // 分页改变
  203. const onHandleSizeChange = (val: number) => {
  204. state.page.pageSize = val;
  205. handleList();
  206. emit('pageChange', state.page);
  207. };
  208. // 改变当前页
  209. const onHandleCurrentChange = (val: number) => {
  210. state.page.page = val;
  211. handleList();
  212. emit('pageChange', state.page);
  213. };
  214. // 列排序
  215. const sortChange = (column: any) => {
  216. state.page.field = column.prop;
  217. state.page.order = column.order;
  218. handleList();
  219. };
  220. // 重置列表
  221. const pageReset = () => {
  222. tableRef.value.clearSelection();
  223. state.page.page = 1;
  224. handleList();
  225. };
  226. // 导出当前页
  227. const onImportTable = () => {
  228. if (setHeader.value.length <= 0) return ElMessage.error('没有勾选要导出的列');
  229. importData(state.data);
  230. };
  231. // 全部导出
  232. const onImportTableAll = async () => {
  233. if (setHeader.value.length <= 0) return ElMessage.error('没有勾选要导出的列');
  234. state.importLoading = true;
  235. const param = Object.assign({}, props.param, { page: 1, pageSize: 99999 });
  236. const res = await props.getData(param);
  237. state.importLoading = false;
  238. const data = res.result?.items ?? [];
  239. importData(data);
  240. };
  241. // 导出方法
  242. const importData = (data: Array<EmptyObjectType>) => {
  243. if (data.length <= 0) return ElMessage.error('没有数据可以导出');
  244. state.importLoading = true;
  245. let exportData = JSON.parse(JSON.stringify(data));
  246. if (props.exportChangeData) {
  247. exportData = props.exportChangeData(exportData);
  248. }
  249. exportExcel(
  250. exportData,
  251. `${props.config.exportFileName ? props.config.exportFileName : themeConfig.value.globalTitle}_${new Date().toLocaleString()}`,
  252. setHeader.value.filter((item) => {
  253. return item.type != 'action';
  254. }),
  255. '导出数据'
  256. );
  257. state.importLoading = false;
  258. };
  259. // 打印
  260. const onPrintTable = () => {
  261. // https://printjs.crabbly.com/#documentation
  262. // 自定义打印
  263. let tableTh = '';
  264. let tableTrTd = '';
  265. let tableTd: any = {};
  266. // 表头
  267. props?.columns.forEach((v: any) => {
  268. if (v.prop === "action") {
  269. return;
  270. }
  271. tableTh += `<th class="table-th">${v.label}</th>`;
  272. });
  273. // 表格内容
  274. state.data.forEach((val: any, key: any) => {
  275. if (!tableTd[key]) tableTd[key] = [];
  276. props.columns.forEach((v: any) => {
  277. if (v.prop === "action") {
  278. return;
  279. }
  280. if (v.type === 'text') {
  281. tableTd[key].push(`<td class="table-th table-center">${val[v.prop]}</td>`);
  282. } else if (v.type === 'image') {
  283. tableTd[key].push(`<td class="table-th table-center"><img src="${val[v.prop]}" style="width:${v.width}px;height:${v.height}px;"/></td>`);
  284. }
  285. });
  286. tableTrTd += `<tr>${tableTd[key].join('')}</tr>`;
  287. });
  288. // 打印
  289. printJs({
  290. printable: `<div style=display:flex;flex-direction:column;text-align:center><h3>${props.printName}</h3></div><table border=1 cellspacing=0><tr>${tableTh}${tableTrTd}</table>`,
  291. type: 'raw-html',
  292. css: ['//at.alicdn.com/t/c/font_2298093_rnp72ifj3ba.css', '//unpkg.com/element-plus/dist/index.css'],
  293. style: `@media print{.mb15{margin-bottom:15px;}.el-button--small i.iconfont{font-size: 12px !important;margin-right: 5px;}}; .table-th{word-break: break-all;white-space: pre-wrap;}.table-center{text-align: center;}`,
  294. });
  295. };
  296. // 刷新
  297. const onRefreshTable = () => {
  298. handleList();
  299. // emit('pageChange', state.page);
  300. };
  301. // 拖拽设置
  302. const onSetTable = () => {
  303. nextTick(() => {
  304. const sortable = Sortable.create(toolSetRef.value, {
  305. handle: '.handle',
  306. dataIdAttr: 'data-key',
  307. animation: 150,
  308. onEnd: () => {
  309. const headerList: EmptyObjectType[] = [];
  310. sortable.toArray().forEach((val: any) => {
  311. props.columns.forEach((v) => {
  312. if (v.prop === val) headerList.push({ ...v });
  313. });
  314. });
  315. emit('sortHeader', headerList);
  316. },
  317. });
  318. });
  319. };
  320. const handleList = async () => {
  321. state.loading = true;
  322. let param = Object.assign({}, props.param, { ...state.page });
  323. // Object.keys(param).forEach((key) => !param[key] && delete param[key]);
  324. Object.keys(param).forEach((key) => (param[key] === undefined) && delete param[key]);
  325. const res = await props.getData(param);
  326. state.loading = false;
  327. if (res && res.result && res.result.items) {
  328. state.showPagination = true;
  329. state.data = res.result?.items ?? [];
  330. state.total = res.result?.total ?? 0;
  331. } else {
  332. state.showPagination = false;
  333. state.data = (res && res.result) ? res.result : [];
  334. }
  335. };
  336. const toggleSelection = (row: any, statu?: boolean) => {
  337. tableRef.value!.toggleRowSelection(row, statu);
  338. };
  339. const getTableData = () => {
  340. return state.data;
  341. }
  342. const setTableData = (data: Array<EmptyObjectType>, add: boolean = false) => {
  343. if (add) { // 追加
  344. //去重
  345. var repeat = false;
  346. for (let newItem of data) {
  347. repeat = false;
  348. for (let item of state.data) {
  349. if (newItem.id === item.id) {
  350. repeat = true;
  351. break;
  352. }
  353. }
  354. if (!repeat) {
  355. state.data.push(newItem);
  356. }
  357. }
  358. } else {
  359. state.data = data;
  360. }
  361. }
  362. onMounted(() => {
  363. if (props.defaultSort) {
  364. state.page.field = props.defaultSort.prop;
  365. state.page.order = props.defaultSort.order;
  366. }
  367. state.page.pageSize = props.config.pageSize;
  368. handleList();
  369. });
  370. // 暴露变量
  371. defineExpose({
  372. pageReset,
  373. handleList,
  374. toggleSelection,
  375. getTableData,
  376. setTableData,
  377. });
  378. </script>
  379. <style scoped lang="scss">
  380. .table-container {
  381. display: flex;
  382. flex-direction: column;
  383. height: 100%;
  384. .el-table {
  385. flex: 1;
  386. }
  387. .table-footer {
  388. display: flex;
  389. justify-content: flex-end;
  390. }
  391. .table-header {
  392. display: flex;
  393. .table-footer-tool {
  394. flex: 1;
  395. display: flex;
  396. align-items: center;
  397. justify-content: flex-end;
  398. i {
  399. margin-right: 10px;
  400. cursor: pointer;
  401. color: var(--el-text-color-regular);
  402. &:last-of-type {
  403. margin-right: 0;
  404. }
  405. }
  406. .el-dropdown {
  407. i {
  408. margin-right: 10px;
  409. color: var(--el-text-color-regular);
  410. }
  411. }
  412. }
  413. }
  414. }
  415. </style>