index.js 13 KB

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