index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. 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.needTotalList = []
  152. this.clearSelected()
  153. this.localPagination = Object.assign({}, {
  154. current: 1, pageSize: this.pageSize, total: 0
  155. })
  156. },
  157. /**
  158. * 加载数据方法
  159. * @param {Object} pagination 分页选项器
  160. * @param {Object} filters 过滤条件
  161. * @param {Object} sorter 排序条件
  162. */
  163. loadData (pagination, filters, sorter) {
  164. this.localLoading = true
  165. const parameter = Object.assign({
  166. pageNo: (pagination && pagination.current) ||
  167. this.showPagination && this.localPagination.current || this.pageNum,
  168. pageSize: (pagination && pagination.pageSize) ||
  169. this.showPagination && this.localPagination.pageSize || this.pageSize,
  170. tableId: this.tableId,
  171. index: this.index
  172. },
  173. (sorter && sorter.field && {
  174. sortField: sorter.field
  175. }) || {},
  176. (sorter && sorter.order && {
  177. sortOrder: sorter.order
  178. }) || {}, {
  179. ...filters
  180. }
  181. )
  182. // console.log('parameter', parameter)
  183. const result = this.data(parameter)
  184. // 对接自己的通用数据接口需要修改下方代码中的 r.pageNo, r.count, r.data
  185. // eslint-disable-next-line
  186. if ((typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
  187. result.then(r => {
  188. // const list = r.list || r.data || r
  189. let list = []
  190. if (r) {
  191. list = r.list || r.data || r
  192. }
  193. // console.log(r,'rrrrrrrrrr')
  194. this.isSucceed = !!r
  195. this.localPagination = this.showPagination && Object.assign({}, this.localPagination, {
  196. current: r.pageNo, // 返回结果中的当前分页数
  197. total: Number(r.count), // 返回结果中的总记录数
  198. showSizeChanger: this.showSizeChanger,
  199. pageSize: (pagination && pagination.pageSize) ||
  200. this.localPagination.pageSize
  201. }) || false
  202. // 为防止删除数据后导致页面当前页面数据长度为 0 ,自动翻页到上一页
  203. if (list.length === 0 && this.showPagination && this.localPagination.current > 1) {
  204. this.localPagination.current--
  205. this.loadData()
  206. return
  207. }
  208. // 这里用于判断接口是否有返回 r.count 且 this.showPagination = true 且 pageNo 和 pageSize 存在 且 count 小于等于 pageNo * pageSize 的大小
  209. // 当情况满足时,表示数据不满足分页大小,关闭 table 分页功能
  210. try {
  211. if ((['auto', true].includes(this.showPagination) && r.count <= (r.pageNo * this.localPagination.pageSize))) {
  212. // this.localPagination.hideOnSinglePage = true
  213. }
  214. } catch (e) {
  215. this.localPagination = false
  216. }
  217. this.localDataSource = list // 返回结果中的数组数据
  218. this.localLoading = false
  219. }).catch(err => {
  220. this.clearTable()
  221. })
  222. }
  223. },
  224. initTotalList (columns) {
  225. const totalList = []
  226. columns && columns instanceof Array && columns.forEach(column => {
  227. if (column.needTotal) {
  228. totalList.push({
  229. ...column,
  230. total: 0
  231. })
  232. }
  233. })
  234. return totalList
  235. },
  236. /**
  237. * 用于更新已选中的列表数据 total 统计
  238. * @param selectedRowKeys
  239. * @param selectedRows
  240. */
  241. updateSelect (selectedRowKeys, selectedRows) {
  242. const list = this.needTotalList
  243. this.needTotalList = list.map(item => {
  244. return {
  245. ...item,
  246. total: this.selectedRows.reduce((sum, val) => {
  247. const total = sum + parseInt(get(val, item.dataIndex))
  248. return isNaN(total) ? 0 : total
  249. }, 0)
  250. }
  251. })
  252. const obj = {
  253. selectedRowKeys: this.selectedRowKeys,
  254. selectedRows: this.selectedRows
  255. }
  256. this.$emit('rowSelection', obj)
  257. },
  258. onSelectChange (record, selected, selectedRows, nativeEvent) {
  259. if (selected) { // 选择
  260. this.selectedRows.push(record)
  261. } else { // 取消
  262. const selectedRowsArr = []
  263. this.selectedRows.map(item => {
  264. if (this.selectedRowKeys.indexOf(item[this.rowKeyName]) != -1) {
  265. selectedRowsArr.push(item)
  266. }
  267. })
  268. this.selectedRows = selectedRowsArr
  269. }
  270. this.updateSelect()
  271. },
  272. // 本页全选/取消全选
  273. onSelectAllChange (selected, selectedRows, changeRows) {
  274. const _this = this
  275. if (selected) { // 选择
  276. this.selectedRows = [...this.selectedRows, ...changeRows]
  277. } else { // 取消
  278. const arrIds = []
  279. changeRows.map((item, index) => {
  280. arrIds.push(item[this.rowKeyName])
  281. })
  282. const arrs = []
  283. this.selectedRows.map((item, index) => {
  284. if (arrIds.indexOf(item[this.rowKeyName]) == -1) {
  285. arrs.push(item)
  286. }
  287. })
  288. this.selectedRows = arrs
  289. }
  290. this.updateSelect()
  291. },
  292. // 设置 table 已选中项
  293. setTableSelected (selectedRowKeys, selectedRows) {
  294. this.selectedRows = selectedRows
  295. this.selectedRowKeys = selectedRowKeys
  296. this.updateSelect()
  297. },
  298. /**
  299. * 清空 table 已选中项
  300. */
  301. clearSelected () {
  302. if (this.rowSelection) {
  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. customRows(record, index) {
  351. return {
  352. // 自定义属性,也就是官方文档中的props,可通过条件来控制样式
  353. style: {
  354. // 设置行背景色
  355. 'background-color': record[this.rowKeyName] == this.leftAlignId ? '#ffedeb' : ''
  356. },
  357. on: {
  358. // 鼠标单击行
  359. click: event => {
  360. // 记录当前点击的行标识
  361. this.leftAlignId = record[this.rowKeyName]
  362. },
  363. dblclick: (event) => {
  364. event.stopPropagation()
  365. this.$emit('dblclick', record, index)
  366. }
  367. }
  368. }
  369. },
  370. },
  371. render () {
  372. const props = {}
  373. const localKeys = Object.keys(this.$data)
  374. const showAlert = (typeof this.alert === 'object' && this.alert !== null && this.alert.show) && typeof this.rowSelection.selectedRowKeys !== 'undefined' || this.alert
  375. Object.keys(T.props).forEach(k => {
  376. const localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`
  377. if (localKeys.includes(localKey)) {
  378. props[k] = this[localKey]
  379. return props[k]
  380. }
  381. if (k === 'rowSelection') {
  382. if (this.rowSelection) {
  383. // 如果需要使用alert,则重新绑定 rowSelection 事件
  384. props[k] = {
  385. ...this.rowSelection,
  386. selectedRowKeys: this.selectedRowKeys,
  387. onChange: (selectedRowKeys, selectedRows) => {
  388. this.selectedRowKeys = selectedRowKeys
  389. },
  390. onSelect: (record, selected, selectedRows, nativeEvent) => {
  391. this.onSelectChange(record, selected, selectedRows, nativeEvent)
  392. },
  393. onSelectAll: (selected, selectedRows, changeRows) => {
  394. this.onSelectAllChange(selected, selectedRows, changeRows)
  395. }
  396. }
  397. return props[k]
  398. } else if (!this.rowSelection) {
  399. // 如果没打算开启 rowSelection 则清空默认的选择项
  400. props[k] = null
  401. return props[k]
  402. }
  403. }
  404. this[k] && (props[k] = this[k])
  405. return props[k]
  406. })
  407. if (!this.isSucceed) { // 请求失败
  408. props['locale'] = { emptyText: '暂时无法获取数据,请刷新页面重试' }
  409. }
  410. // isSucceed
  411. const table = (
  412. <a-table {...{ props, scopedSlots: { ...this.$scopedSlots } }} customRow={this.customRows} onChange={this.loadData} onExpand={this.expandFun}>
  413. { Object.keys(this.$slots).map(name => (<template slot={name}>{this.$slots[name]}</template>)) }
  414. </a-table>
  415. )
  416. return (
  417. <div class="table-wrapper">
  418. { showAlert ? this.renderAlert() : null }
  419. { table }
  420. </div>
  421. )
  422. }
  423. }