index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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.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 selectedRowsArr = []
  279. this.selectedRows.map((item, index) => {
  280. if(!changeRows.find(subItem => subItem[this.rowKeyName] == item[this.rowKeyName])){
  281. selectedRowsArr.push(item)
  282. }
  283. })
  284. this.selectedRows = selectedRowsArr
  285. }
  286. this.updateSelect()
  287. },
  288. // 设置 table 已选中项
  289. setTableSelected (selectedRowKeys, selectedRows) {
  290. this.selectedRows = selectedRows
  291. this.selectedRowKeys = selectedRowKeys
  292. this.updateSelect()
  293. },
  294. /**
  295. * 清空 table 已选中项
  296. */
  297. clearSelected () {
  298. if (this.rowSelection) {
  299. this.selectedRows = []
  300. this.selectedRowKeys = []
  301. this.updateSelect()
  302. }
  303. },
  304. /**
  305. * 处理交给 table 使用者去处理 clear 事件时,内部选中统计同时调用
  306. * @param callback
  307. * @returns {*}
  308. */
  309. renderClear (callback) {
  310. if (this.selectedRowKeys.length <= 0) return null
  311. return (
  312. <a style="margin-left: 24px" onClick={() => {
  313. callback()
  314. this.clearSelected()
  315. }}>清空</a>
  316. )
  317. },
  318. renderAlert () {
  319. // 绘制统计列数据
  320. const needTotalItems = this.needTotalList.map((item) => {
  321. return (<span style="margin-right: 12px">
  322. {item.title}总计 <a style="font-weight: 600">{!item.customRender ? item.total : item.customRender(item.total)}</a>
  323. </span>)
  324. })
  325. // 绘制 清空 按钮
  326. const clearItem = (typeof this.alert.clear === 'boolean' && this.alert.clear) ? (
  327. this.renderClear(this.clearSelected)
  328. ) : (this.alert !== null && typeof this.alert.clear === 'function') ? (
  329. this.renderClear(this.alert.clear)
  330. ) : null
  331. // 绘制 alert 组件
  332. return (
  333. <a-alert showIcon={true} style="margin-bottom: 16px">
  334. <template slot="message">
  335. <span style="margin-right: 12px">已选择: <a style="font-weight: 600">{this.selectedRows.length}</a></span>
  336. {needTotalItems}
  337. {clearItem}
  338. </template>
  339. </a-alert>
  340. )
  341. }
  342. },
  343. render () {
  344. const props = {}
  345. const localKeys = Object.keys(this.$data)
  346. const showAlert = (typeof this.alert === 'object' && this.alert !== null && this.alert.show) && typeof this.rowSelection.selectedRowKeys !== 'undefined' || this.alert
  347. Object.keys(T.props).forEach(k => {
  348. const localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`
  349. if (localKeys.includes(localKey)) {
  350. props[k] = this[localKey]
  351. return props[k]
  352. }
  353. if (k === 'rowSelection') {
  354. if (this.rowSelection) {
  355. // 如果需要使用alert,则重新绑定 rowSelection 事件
  356. props[k] = {
  357. ...this.rowSelection,
  358. selectedRowKeys: this.selectedRowKeys,
  359. onChange: (selectedRowKeys, selectedRows) => {
  360. this.selectedRowKeys = selectedRowKeys
  361. },
  362. onSelect: (record, selected, selectedRows, nativeEvent) => {
  363. this.onSelectChange(record, selected, selectedRows, nativeEvent)
  364. },
  365. onSelectAll: (selected, selectedRows, changeRows) => {
  366. this.onSelectAllChange(selected, selectedRows, changeRows)
  367. }
  368. }
  369. return props[k]
  370. } else if (!this.rowSelection) {
  371. // 如果没打算开启 rowSelection 则清空默认的选择项
  372. props[k] = null
  373. return props[k]
  374. }
  375. }
  376. this[k] && (props[k] = this[k])
  377. return props[k]
  378. })
  379. if (!this.isSucceed) { // 请求失败
  380. props['locale'] = { emptyText: '网络异常,请点击按钮刷新' }
  381. }
  382. // isSucceed
  383. const table = (
  384. <a-table {...{ props, scopedSlots: { ...this.$scopedSlots } }} onChange={this.loadData}>
  385. { Object.keys(this.$slots).map(name => (<template slot={name}>{this.$slots[name]}</template>)) }
  386. </a-table>
  387. )
  388. return (
  389. <div class="table-wrapper">
  390. { showAlert ? this.renderAlert() : null }
  391. { table }
  392. </div>
  393. )
  394. }
  395. }