index.js 13 KB

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