index.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. <template>
  2. <div class="v-table">
  3. <a-spin :spinning="localLoading" tip="Loading...">
  4. <ve-table
  5. ref="tableRef"
  6. style="width:100%;word-break:break-all;"
  7. :max-height="scroll.y"
  8. :scroll-width="scroll.x"
  9. :columns="veColumns"
  10. :table-data="localDataSource"
  11. :row-key-field-name="rowKeyName"
  12. :border-x="true"
  13. :border-y="bordered"
  14. :border-around="bordered"
  15. :column-width-resize-option="columnWidthResizeOption"
  16. :cell-style-option="cellStyleOption"
  17. :row-style-option="{clickHighlight: true}"
  18. :cellSelectionOption="{enable: false}"
  19. :virtual-scroll-option="{enable: !showPagination}"
  20. :sort-option="sortOption"
  21. :checkbox-option="checkboxOption"
  22. :event-custom-option="eventCustomOption"
  23. />
  24. <div v-show="localDataSource.length==0" :style="{height:(showPagination?scroll.y-35:scroll.y)+'px',position:!showPagination?'absolute':'relative',top:!showPagination?0:''}" class="empty-data"><a-empty description="暂无数据" :image="simpleImage"/></div>
  25. <div class="v-pagination" :class="'v-pagination-align-'+pageAlign">
  26. <div class="v-page-left" v-if="pageAlign=='right'"><slot name="page"></slot></div>
  27. <div class="v-page-no" v-if="showPagination&&localPagination.total">
  28. <a-pagination
  29. size="small"
  30. :total="localPagination.total"
  31. v-model="localPagination.current"
  32. :pageSize="localPagination.pageSize"
  33. :showTotal="total => `共 ${total} 条记录`"
  34. :pageSizeOptions="['10', '20', '30', '40', '50', '100', '300', '500']"
  35. :show-quick-jumper="localPagination.showQuickJumper"
  36. @change="paginationChange"
  37. show-size-changer
  38. @showSizeChange="paginationShowSizeChange"
  39. />
  40. </div>
  41. <div class="v-page-right" v-if="pageAlign=='left'"><slot name="page"></slot></div>
  42. </div>
  43. </a-spin>
  44. </div>
  45. </template>
  46. <script>
  47. import { Empty } from 'ant-design-vue'
  48. export default {
  49. name: 'VTable',
  50. props: {
  51. // 列
  52. columns: {
  53. type: Array,
  54. default: () => []
  55. },
  56. // load data function
  57. data: {
  58. type: Function,
  59. required: false
  60. },
  61. // 数据
  62. dataSource: {
  63. type: Array,
  64. default: () => []
  65. },
  66. // 默认是否加载表格数据
  67. defaultLoadData: {
  68. type: Boolean,
  69. default: true
  70. },
  71. // 表格宽度和高度
  72. scroll: {
  73. type: Object,
  74. default: () => { return { x: 0, y: 400 } }
  75. },
  76. // 是否显示边框
  77. bordered: {
  78. type: Boolean,
  79. default: true
  80. },
  81. // 表格默认key name
  82. rowKeyName: {
  83. type: String,
  84. default: 'id'
  85. },
  86. // 分页配置
  87. pagination: {
  88. type: Object
  89. },
  90. // 是否显示分页
  91. showPagination: {
  92. type: Boolean,
  93. default: true
  94. },
  95. // 分页对齐方式,left ,center,right
  96. pageAlign: {
  97. type: String,
  98. default: 'center'
  99. },
  100. // 是否开启多选
  101. rowSelection: {
  102. type: Object,
  103. default: () => null
  104. },
  105. disableSelectedRowKeys: {
  106. type: Array,
  107. default: () => []
  108. }
  109. },
  110. computed: {
  111. veColumns () {
  112. return this.convertColumns(this.columns)
  113. },
  114. // 表格复选框设置
  115. checkboxOption () {
  116. return {
  117. disableSelectedRowKeys: this.disableSelectedRowKeys,
  118. selectedRowKeys: this.selectedRowKeys,
  119. // 行选择改变事件
  120. selectedRowChange: ({ row, isSelected, selectedRowKeys }) => {
  121. this.selectedRowChange({ row, isSelected, selectedRowKeys })
  122. },
  123. // 全选改变事件
  124. selectedAllChange: ({ isSelected, selectedRowKeys }) => {
  125. this.selectedAllChange({ isSelected, selectedRowKeys })
  126. }
  127. }
  128. }
  129. },
  130. data () {
  131. return {
  132. localLoading: false,
  133. simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
  134. localDataSource: [],
  135. sortObj: null,
  136. isSucceed: true, // 是否请求成功
  137. // 拖到列宽
  138. columnWidthResizeOption: {
  139. // default false
  140. enable: true,
  141. // column resize min width
  142. minWidth: 30,
  143. // column size change
  144. sizeChange: ({ column, differWidth, columnWidth }) => {}
  145. },
  146. // 单元格样式
  147. cellStyleOption: {
  148. bodyCellClass: ({ row, column, rowIndex }) => {}
  149. },
  150. // 排序
  151. sortOption: {
  152. // sort always
  153. sortAlways: false,
  154. sortChange: (params) => {
  155. this.sortChange(params)
  156. }
  157. },
  158. // 分页
  159. localPagination: Object.assign({
  160. current: 1,
  161. pageSize: 10,
  162. showSizeChanger: true,
  163. showQuickJumper: false
  164. }, this.pagination),
  165. // 选中的项
  166. selectedRowKeys: [],
  167. selectedRows: [],
  168. eventCustomOption: {
  169. bodyRowEvents: ({ row, column, rowIndx }) => {
  170. return {
  171. click: (event) => {
  172. this.$emit('rowClick', event, row, rowIndx)
  173. },
  174. dblclick: (event) => {
  175. this.$emit('dblRowClick', event, row, rowIndx)
  176. },
  177. contextmenu: (event) => {},
  178. mouseenter: (event) => {},
  179. mouseleave: (event) => {},
  180. mousemove: (event) => {},
  181. mouseover: (event) => {},
  182. mousedown: (event) => {},
  183. mouseup: (event) => {}
  184. }
  185. }
  186. }
  187. }
  188. },
  189. created () {
  190. if (this.defaultLoadData && this.data) {
  191. this.loadData()
  192. }
  193. if (!this.data) {
  194. this.localDataSource = this.dataSource
  195. }
  196. },
  197. watch: {
  198. dataSource: {
  199. handler () {
  200. this.localDataSource = this.dataSource
  201. },
  202. deep: true
  203. }
  204. },
  205. methods: {
  206. // 选择单元格
  207. selectedRowChange ({ row, isSelected, selectedRowKeys }) {
  208. // console.log(isSelected, selectedRowKeys)
  209. // 选中
  210. if (isSelected) {
  211. this.selectedRows.push(row)
  212. } else {
  213. // 取消
  214. this.selectedRows = this.selectedRows.filter(item => item[this.rowKeyName] !== row[this.rowKeyName])
  215. }
  216. this.selectedRowKeys = selectedRowKeys
  217. this.onRowSelection()
  218. this.$emit('selectRowChange', { row, isSelected, selectedRowKeys })
  219. },
  220. // 全选或取消本页行
  221. selectedAllChange ({ isSelected, selectedRowKeys }) {
  222. // console.log(isSelected, selectedRowKeys)
  223. // 全选
  224. if (isSelected) {
  225. // 合并数组,并去重
  226. this.selectedRows = this.selectedRows.concat(this.localDataSource).reduce((prev, next) => {
  227. if (!prev.find(item => item[this.rowKeyName] === next[this.rowKeyName])) {
  228. prev.push(next)
  229. }
  230. return prev
  231. }, [])
  232. } else {
  233. // 取消全选,删除当前页选项
  234. const changeRowKeys = this.localDataSource.map(item => item[this.rowKeyName])
  235. this.selectedRows = this.selectedRows.filter(item => !changeRowKeys.includes(item[this.rowKeyName]))
  236. }
  237. this.selectedRowKeys = selectedRowKeys
  238. this.onRowSelection()
  239. this.$emit('selectAllRowChange', { isSelected, selectedRowKeys })
  240. },
  241. // 触发已选项事件
  242. onRowSelection () {
  243. // console.log(this.selectedRows)
  244. const selectedRowKeys = this.selectedRows.map(item => item[this.rowKeyName])
  245. this.$emit('rowSelection', { selectedRows: this.selectedRows, selectedRowKeys: selectedRowKeys })
  246. },
  247. // 页码改变的时候设置新页的已选项
  248. setCheckedRows () {
  249. const list = this.selectedRows.map(item => item[this.rowKeyName])
  250. this.selectedRowKeys = this.localDataSource.filter(item => list.includes(item[this.rowKeyName])).map(item => item[this.rowKeyName])
  251. },
  252. /**
  253. * 清空 table 已选中项
  254. */
  255. clearSelected () {
  256. this.selectedRowKeys = []
  257. this.selectedRows = []
  258. },
  259. // 设置 table 已选中项
  260. setTableSelected (selectedRowKeys) {
  261. this.selectedRows = selectedRowKeys.map(item => { const obj = {}; obj[this.rowKeyName] = item; return obj })
  262. this.setCheckedRows()
  263. },
  264. // 通过key.key...获取属性值
  265. getNestedPropertyValue (obj, path) {
  266. return path.split('.').reduce(function (o, p) {
  267. if (!o) return
  268. return o[p]
  269. }, obj || {})
  270. },
  271. // 转换colums数据结构,兼容老页面
  272. convertColumns (columns) {
  273. const ret = []
  274. const _this = this
  275. for (let i = 0; i < columns.length; i++) {
  276. const item = columns[i]
  277. const windowWidth = window.innerWidth - 200
  278. ret.push({
  279. field: item.field || item.dataIndex,
  280. key: item.key || 'col-' + i,
  281. title: item.title,
  282. // 自定义头部单元格表头
  283. renderHeaderCell: ({ column }, h) => {
  284. if (item.slots) {
  285. return _this.$scopedSlots[item.slots.title]()
  286. }
  287. if (item.align != 'center') {
  288. return (
  289. <div style="text-align:center;">{column.title}</div>
  290. )
  291. }
  292. return h('span', column.title)
  293. },
  294. width: String(item.width).indexOf('%') >= 0 ? Number(String(item.width).replace('%', '') * windowWidth / 100) : Number(String(item.width).replace('px', '')), // 百分比转数字
  295. align: item.align,
  296. fixed: item.fixed,
  297. sortBy: item.sortBy || item.sorter ? '' : undefined,
  298. children: item.children ? _this.convertColumns(item.children) : undefined,
  299. // 自定义单元格
  300. scopedSlotsKey: item.scopedSlots && item.scopedSlots.customRender,
  301. hasEllipsis: item.ellipsis,
  302. renderBodyCell: ({ row, column, rowIndex }, h) => {
  303. // 如果field 是obj.objkey.objkey...形式
  304. const text = column.field ? (column.field.indexOf('.') >= 0 ? _this.getNestedPropertyValue(row, column.field) : row[column.field]) : null
  305. // 有自定义单元格
  306. if (column.scopedSlotsKey) {
  307. return _this.$scopedSlots[column.scopedSlotsKey](text, row, rowIndex, column)
  308. }
  309. // 省略字符
  310. if (item.ellipsis && column.field && text) {
  311. return (
  312. <a-tooltip placement="right">
  313. <template slot="title">
  314. <span>{text}</span>
  315. </template>
  316. <span class="ve-table-body-td-span-ellipsis" style="-webkit-line-clamp: 1;">{text || '--'}</span>
  317. </a-tooltip>
  318. )
  319. }
  320. return item.customRender ? item.customRender(text) : text || '--'
  321. }
  322. })
  323. }
  324. // 判断是否开启多选框
  325. const hasCheckbox = ret.find(item => item.type == 'checkbox')
  326. // 兼容老版本表格
  327. if (!hasCheckbox && this.rowSelection) {
  328. ret.unshift({ title: '', field: 'checkbox', key: 'checkbox', width: 20, type: 'checkbox', align: 'center' })
  329. }
  330. return ret
  331. },
  332. /**
  333. * 加载数据方法
  334. * @param {Object} pagination 分页选项器
  335. * @param {Object} filters 过滤条件
  336. * @param {Object} sorter 排序条件
  337. */
  338. loadData (pagination, filters, sorter) {
  339. this.localLoading = true
  340. const parameter = Object.assign({
  341. pageNo: this.showPagination && this.localPagination.current || 1,
  342. pageSize: this.showPagination && this.localPagination.pageSize || 10
  343. },
  344. this.sortObj && { sortField: this.sortObj.field, sortOrder: this.sortObj.order } || {}
  345. )
  346. const result = this.data(parameter)
  347. // 对接自己的通用数据接口需要修改下方代码中的 r.pageNo, r.count, r.data
  348. if ((typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
  349. result.then(r => {
  350. const list = r.list || r.data || r || []
  351. this.isSucceed = !!r
  352. this.localPagination = this.showPagination && Object.assign({}, this.localPagination, {
  353. current: r.pageNo || 1, // 返回结果中的当前分页数
  354. total: Number(r.count) || 0, // 返回结果中的总记录数
  355. pageSize: r.pageSize || this.localPagination.pageSize
  356. }) || false
  357. // 为防止删除数据后导致页面当前页面数据长度为 0 ,自动翻页到上一页
  358. if (list.length === 0 && this.showPagination && this.localPagination.current > 1) {
  359. this.localPagination.current--
  360. this.loadData()
  361. return
  362. }
  363. // 这里用于判断接口是否有返回 r.count 且 this.showPagination = true 且 pageNo 和 pageSize 存在 且 count 小于等于 pageNo * pageSize 的大小
  364. // 当情况满足时,表示数据不满足分页大小,关闭 table 分页功能
  365. try {
  366. if ((['auto', true].includes(this.showPagination) && r.count <= (r.pageNo * this.localPagination.pageSize))) {
  367. // this.localPagination.hideOnSinglePage = true
  368. }
  369. } catch (e) {
  370. this.localPagination = false
  371. }
  372. this.localDataSource = list // 返回结果中的数组数据
  373. this.setCheckedRows()
  374. this.localLoading = false
  375. }).catch(err => {
  376. this.clearTable()
  377. })
  378. }
  379. },
  380. // 页码变更
  381. paginationChange (pageNumber) {
  382. this.localPagination.current = pageNumber
  383. this.loadData()
  384. },
  385. paginationShowSizeChange (current, pageSize) {
  386. this.localPagination.current = current
  387. this.localPagination.pageSize = pageSize
  388. this.loadData()
  389. },
  390. // 排序
  391. sortChange (params) {
  392. this.sortObj = null
  393. for (const a in params) {
  394. if (params[a]) {
  395. this.sortObj = {
  396. field: a,
  397. order: params[a] + 'end'
  398. }
  399. }
  400. }
  401. this.loadData()
  402. },
  403. /**
  404. * 表格重新加载方法
  405. * 如果参数为 true, 则强制刷新到第一页
  406. * @param Boolean bool
  407. */
  408. refresh (bool = false) {
  409. bool && (this.localPagination = Object.assign({}, {
  410. current: 1, pageSize: this.localPagination.pageSize
  411. }))
  412. this.loadData()
  413. },
  414. // 清空表格为空
  415. clearTable () {
  416. this.localLoading = false
  417. this.localDataSource = []
  418. this.sortObj = null
  419. this.clearSelected()
  420. this.localPagination = Object.assign({}, {
  421. current: 1, pageSize: this.localPagination.pageSize, total: 0
  422. })
  423. }
  424. }
  425. }
  426. </script>
  427. <style lang="less" scoped>
  428. .v-table {
  429. width: 100%;
  430. > div{
  431. height: 100%;
  432. }
  433. .ant-spin-container{
  434. height: 100%;
  435. }
  436. .empty-data{
  437. color: #999;
  438. text-align: center;
  439. width: 100%;
  440. display: flex;
  441. align-items: center;
  442. flex-direction: column;
  443. justify-content: center;
  444. }
  445. .v-pagination{
  446. display:flex;
  447. align-items: center;
  448. }
  449. .v-pagination-align-right{
  450. justify-content: space-between;
  451. }
  452. .v-pagination-align-left{
  453. justify-content: space-between;
  454. }
  455. .v-pagination-align-center{
  456. justify-content: center;
  457. }
  458. .v-page-no{
  459. padding: 10px 0;
  460. }
  461. /deep/ .ve-table .ve-table-container .ve-table-content-wrapper table.ve-table-content tbody.ve-table-body tr.ve-table-body-tr td.ve-table-body-td,
  462. .ve-table .ve-table-container .ve-table-content-wrapper table.ve-table-content tbody.ve-table-body tr.ve-table-expand-tr td.ve-table-body-td{
  463. div:empty::before {
  464. content:'--'
  465. }
  466. }
  467. }
  468. </style>