index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import T from 'ant-design-vue/es/table/Table'
  2. import get from 'lodash.get'
  3. export default {
  4. data () {
  5. return {
  6. needTotalList: [],
  7. selectedRows: [],
  8. selectedRowKeys: [],
  9. localLoading: false,
  10. localDataSource: [],
  11. localPagination: Object.assign({}, this.pagination),
  12. isSucceed: true // 是否请求成功
  13. }
  14. },
  15. props: Object.assign({}, T.props, {
  16. rowKey: {
  17. type: [String, Function],
  18. default: 'key'
  19. },
  20. rowKeyName: { // 多选时,唯一标识键名
  21. type: String,
  22. default: 'id'
  23. },
  24. rowClassName: {
  25. type: [String, Function],
  26. default: ''
  27. },
  28. data: {
  29. type: Function,
  30. required: true
  31. },
  32. pageNum: {
  33. type: Number,
  34. default: 1
  35. },
  36. pageSize: {
  37. type: Number,
  38. default: 20
  39. },
  40. showSizeChanger: {
  41. type: Boolean,
  42. default: true
  43. },
  44. size: {
  45. type: String,
  46. default: 'default'
  47. },
  48. /**
  49. * alert: {
  50. * show: true,
  51. * clear: Function
  52. * }
  53. */
  54. alert: {
  55. type: [Object, Boolean],
  56. default: null
  57. },
  58. rowSelection: {
  59. type: Object,
  60. default: null
  61. },
  62. showPagination: {
  63. type: String | Boolean,
  64. default: 'auto'
  65. },
  66. /**
  67. * enable page URI mode
  68. *
  69. * e.g:
  70. * /users/1
  71. * /users/2
  72. * /users/3?queryParam=test
  73. * ...
  74. */
  75. pageURI: {
  76. type: Boolean,
  77. default: false
  78. },
  79. /** 是否首次加载数据 */
  80. defaultLoadData: {
  81. type: Boolean,
  82. default: true
  83. },
  84. tableId: {
  85. type: String,
  86. default: ''
  87. },
  88. index: {
  89. type: [String, Number],
  90. default: ''
  91. }
  92. }),
  93. watch: {
  94. 'localPagination.current' (val) {
  95. this.pageURI && this.$router.push({
  96. ...this.$route,
  97. name: this.$route.name,
  98. params: Object.assign({}, this.$route.params, {
  99. pageNo: val
  100. })
  101. })
  102. },
  103. pageNum (val) {
  104. Object.assign(this.localPagination, {
  105. current: val
  106. })
  107. },
  108. pageSize (val) {
  109. Object.assign(this.localPagination, {
  110. pageSize: val
  111. })
  112. },
  113. showSizeChanger (val) {
  114. Object.assign(this.localPagination, {
  115. showSizeChanger: val
  116. })
  117. }
  118. },
  119. created () {
  120. const { pageNo } = this.$route.params
  121. const localPageNum = this.pageURI && (pageNo && parseInt(pageNo)) || this.pageNum
  122. this.localPagination = ['auto', true].includes(this.showPagination) && Object.assign({}, this.localPagination, {
  123. current: localPageNum,
  124. pageSize: this.pageSize,
  125. pageSizeOptions: ['5', '10', '20', '30', '40'],
  126. showTotal: total => `共 ${total} 条记录`,
  127. showSizeChanger: this.showSizeChanger
  128. }) || false
  129. // console.log('this.localPagination', this.localPagination)
  130. this.needTotalList = this.initTotalList(this.columns)
  131. if (this.defaultLoadData) {
  132. this.loadData()
  133. }
  134. },
  135. methods: {
  136. /**
  137. * 表格重新加载方法
  138. * 如果参数为 true, 则强制刷新到第一页
  139. * @param Boolean bool
  140. */
  141. refresh (bool = false) {
  142. bool && (this.localPagination = Object.assign({}, {
  143. current: 1, pageSize: this.pageSize
  144. }))
  145. this.loadData()
  146. },
  147. // 重置表格为空
  148. clearTable () {
  149. this.localLoading = false
  150. this.localDataSource = []
  151. this.localPagination = Object.assign({}, {
  152. current: 1, pageSize: this.pageSize, total: 0
  153. })
  154. },
  155. /**
  156. * 加载数据方法
  157. * @param {Object} pagination 分页选项器
  158. * @param {Object} filters 过滤条件
  159. * @param {Object} sorter 排序条件
  160. */
  161. loadData (pagination, filters, sorter) {
  162. this.localLoading = true
  163. const parameter = Object.assign({
  164. pageNo: (pagination && pagination.current) ||
  165. this.showPagination && this.localPagination.current || this.pageNum,
  166. pageSize: (pagination && pagination.pageSize) ||
  167. this.showPagination && this.localPagination.pageSize || this.pageSize,
  168. tableId: this.tableId,
  169. index: this.index
  170. },
  171. (sorter && sorter.field && {
  172. sortField: sorter.field
  173. }) || {},
  174. (sorter && sorter.order && {
  175. sortOrder: sorter.order
  176. }) || {}, {
  177. ...filters
  178. }
  179. )
  180. // console.log('parameter', parameter)
  181. const result = this.data(parameter)
  182. // 对接自己的通用数据接口需要修改下方代码中的 r.pageNo, r.count, r.data
  183. // eslint-disable-next-line
  184. if ((typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
  185. result.then(r => {
  186. // const list = r.list || r.data || r
  187. let list = []
  188. if (r) {
  189. list = r.list || r.data || r
  190. }
  191. // console.log(r,'rrrrrrrrrr')
  192. this.isSucceed = !!r
  193. this.localPagination = this.showPagination && Object.assign({}, this.localPagination, {
  194. current: r.pageNo, // 返回结果中的当前分页数
  195. total: Number(r.count), // 返回结果中的总记录数
  196. showSizeChanger: this.showSizeChanger,
  197. pageSize: (pagination && pagination.pageSize) ||
  198. this.localPagination.pageSize
  199. }) || false
  200. // 为防止删除数据后导致页面当前页面数据长度为 0 ,自动翻页到上一页
  201. if (list.length === 0 && this.showPagination && this.localPagination.current > 1) {
  202. this.localPagination.current--
  203. this.loadData()
  204. return
  205. }
  206. // 这里用于判断接口是否有返回 r.count 且 this.showPagination = true 且 pageNo 和 pageSize 存在 且 count 小于等于 pageNo * pageSize 的大小
  207. // 当情况满足时,表示数据不满足分页大小,关闭 table 分页功能
  208. try {
  209. if ((['auto', true].includes(this.showPagination) && r.count <= (r.pageNo * this.localPagination.pageSize))) {
  210. // this.localPagination.hideOnSinglePage = true
  211. }
  212. } catch (e) {
  213. this.localPagination = false
  214. }
  215. this.localDataSource = list // 返回结果中的数组数据
  216. this.localLoading = false
  217. }).catch(err => {
  218. this.clearTable()
  219. })
  220. }
  221. },
  222. initTotalList (columns) {
  223. const totalList = []
  224. columns && columns instanceof Array && columns.forEach(column => {
  225. if (column.needTotal) {
  226. totalList.push({
  227. ...column,
  228. total: 0
  229. })
  230. }
  231. })
  232. return totalList
  233. },
  234. /**
  235. * 用于更新已选中的列表数据 total 统计
  236. * @param selectedRowKeys
  237. * @param selectedRows
  238. */
  239. updateSelect (selectedRowKeys, selectedRows) {
  240. const list = this.needTotalList
  241. this.needTotalList = list.map(item => {
  242. return {
  243. ...item,
  244. total: this.selectedRows.reduce((sum, val) => {
  245. const total = sum + parseInt(get(val, item.dataIndex))
  246. return isNaN(total) ? 0 : total
  247. }, 0)
  248. }
  249. })
  250. const obj = {
  251. selectedRowKeys: this.selectedRowKeys,
  252. selectedRows: this.selectedRows
  253. }
  254. this.$emit('rowSelection', obj)
  255. },
  256. onSelectChange (record, selected, selectedRows, nativeEvent) {
  257. if (selected) { // 选择
  258. this.selectedRows.push(record)
  259. } else { // 取消
  260. const selectedRowsArr = []
  261. this.selectedRows.map(item => {
  262. if (this.selectedRowKeys.indexOf(item[this.rowKeyName]) != -1) {
  263. selectedRowsArr.push(item)
  264. }
  265. })
  266. this.selectedRows = selectedRowsArr
  267. }
  268. this.updateSelect()
  269. },
  270. // 本页全选/取消全选
  271. onSelectAllChange (selected, selectedRows, changeRows) {
  272. const _this = this
  273. if (selected) { // 选择
  274. this.selectedRows = [...this.selectedRows, ...changeRows]
  275. } else { // 取消
  276. const arrId = []
  277. this.selectedRows.map((item, index) => {
  278. this.selectedRows.map((subItem, ind) => {
  279. if (item[this.rowKeyName] == subItem[this.rowKeyName]) {
  280. arrId.push(index)
  281. }
  282. })
  283. })
  284. arrId.map((item, index) => {
  285. _this.selectedRows = _this.selectedRows.slice(item, item + 1)
  286. })
  287. }
  288. this.updateSelect()
  289. },
  290. // 设置 table 已选中项
  291. setTableSelected (selectedRowKeys, selectedRows) {
  292. this.selectedRows = selectedRows
  293. this.selectedRowKeys = selectedRowKeys
  294. this.updateSelect()
  295. },
  296. /**
  297. * 清空 table 已选中项
  298. */
  299. clearSelected () {
  300. if (this.rowSelection) {
  301. // this.rowSelection.onChange([], [])
  302. // this.updateSelect([], [])
  303. this.selectedRows = []
  304. this.selectedRowKeys = []
  305. this.updateSelect()
  306. }
  307. },
  308. /**
  309. * 处理交给 table 使用者去处理 clear 事件时,内部选中统计同时调用
  310. * @param callback
  311. * @returns {*}
  312. */
  313. renderClear (callback) {
  314. if (this.selectedRowKeys.length <= 0) return null
  315. return (
  316. <a style="margin-left: 24px" onClick={() => {
  317. callback()
  318. this.clearSelected()
  319. }}>清空</a>
  320. )
  321. },
  322. renderAlert () {
  323. // 绘制统计列数据
  324. const needTotalItems = this.needTotalList.map((item) => {
  325. return (<span style="margin-right: 12px">
  326. {item.title}总计 <a style="font-weight: 600">{!item.customRender ? item.total : item.customRender(item.total)}</a>
  327. </span>)
  328. })
  329. // 绘制 清空 按钮
  330. const clearItem = (typeof this.alert.clear === 'boolean' && this.alert.clear) ? (
  331. this.renderClear(this.clearSelected)
  332. ) : (this.alert !== null && typeof this.alert.clear === 'function') ? (
  333. this.renderClear(this.alert.clear)
  334. ) : null
  335. // 绘制 alert 组件
  336. return (
  337. <a-alert showIcon={true} style="margin-bottom: 16px">
  338. <template slot="message">
  339. <span style="margin-right: 12px">已选择: <a style="font-weight: 600">{this.selectedRows.length}</a></span>
  340. {needTotalItems}
  341. {clearItem}
  342. </template>
  343. </a-alert>
  344. )
  345. },
  346. expandFun (expanded, record) {
  347. this.$emit('expand', expanded, record)
  348. }
  349. },
  350. render () {
  351. const props = {}
  352. const localKeys = Object.keys(this.$data)
  353. const showAlert = (typeof this.alert === 'object' && this.alert !== null && this.alert.show) && typeof this.rowSelection.selectedRowKeys !== 'undefined' || this.alert
  354. Object.keys(T.props).forEach(k => {
  355. const localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`
  356. if (localKeys.includes(localKey)) {
  357. props[k] = this[localKey]
  358. return props[k]
  359. }
  360. if (k === 'rowSelection') {
  361. if (this.rowSelection) {
  362. // 如果需要使用alert,则重新绑定 rowSelection 事件
  363. props[k] = {
  364. ...this.rowSelection,
  365. selectedRowKeys: this.selectedRowKeys,
  366. onChange: (selectedRowKeys, selectedRows) => {
  367. this.selectedRowKeys = selectedRowKeys
  368. },
  369. onSelect: (record, selected, selectedRows, nativeEvent) => {
  370. this.onSelectChange(record, selected, selectedRows, nativeEvent)
  371. },
  372. onSelectAll: (selected, selectedRows, changeRows) => {
  373. this.onSelectAllChange(selected, selectedRows, changeRows)
  374. }
  375. }
  376. return props[k]
  377. } else if (!this.rowSelection) {
  378. // 如果没打算开启 rowSelection 则清空默认的选择项
  379. props[k] = null
  380. return props[k]
  381. }
  382. }
  383. this[k] && (props[k] = this[k])
  384. return props[k]
  385. })
  386. if (!this.isSucceed) { // 请求失败
  387. props['locale'] = { emptyText: '暂时无法获取数据,请刷新页面重试' }
  388. }
  389. // isSucceed
  390. const table = (
  391. <a-table {...{ props, scopedSlots: { ...this.$scopedSlots } }} onChange={this.loadData} onExpand={this.expandFun}>
  392. { Object.keys(this.$slots).map(name => (<template slot={name}>{this.$slots[name]}</template>)) }
  393. </a-table>
  394. )
  395. return (
  396. <div class="table-wrapper">
  397. { showAlert ? this.renderAlert() : null }
  398. { table }
  399. </div>
  400. )
  401. }
  402. }