index.js 14 KB

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