table.vue
40.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
<template>
<div :class="wrapClasses" :style="styles">
<div :class="classes">
<div :class="[prefixCls + '-title']" v-if="showSlotHeader" ref="title"><slot name="header"></slot></div>
<div :class="[prefixCls + '-header']" v-if="showHeader" ref="header" @mousewheel="handleMouseWheel">
<table-head
:prefix-cls="prefixCls"
:styleObject="tableHeaderStyle"
:columns="cloneColumns"
:column-rows="columnRows"
:obj-data="objData"
:columns-width="columnsWidth"
:data="rebuildData"></table-head>
</div>
<div :class="[prefixCls + '-body']" :style="bodyStyle" ref="body" @scroll="handleBodyScroll"
v-show="!((!!localeNoDataText && (!data || data.length === 0)) || (!!localeNoFilteredDataText && (!rebuildData || rebuildData.length === 0)))">
<table-body
ref="tbody"
:draggable="draggable"
:prefix-cls="prefixCls"
:styleObject="tableStyle"
:columns="cloneColumns"
:data="rebuildData"
:columns-width="columnsWidth"
:obj-data="objData"></table-body>
</div>
<div
:class="[prefixCls + '-tip']" :style="bodyStyle" @scroll="handleBodyScroll"
v-show="((!!localeNoDataText && (!data || data.length === 0)) || (!!localeNoFilteredDataText && (!rebuildData || rebuildData.length === 0)))">
<table cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td :style="{'height':bodyStyle.height,'width':`${this.headerWidth}px`}">
<span v-html="localeNoDataText" v-if="!data || data.length === 0"></span>
<span v-html="localeNoFilteredDataText" v-else></span>
</td>
</tr>
</tbody>
</table>
</div>
<div :class="[prefixCls + '-fixed']" :style="fixedTableStyle" v-if="isLeftFixed">
<div :class="fixedHeaderClasses" v-if="showHeader">
<table-head
fixed="left"
:prefix-cls="prefixCls"
:styleObject="fixedTableStyle"
:columns="leftFixedColumns"
:column-rows="columnRows"
:fixed-column-rows="leftFixedColumnRows"
:obj-data="objData"
:columns-width="columnsWidth"
:data="rebuildData"></table-head>
</div>
<div :class="[prefixCls + '-fixed-body']" :style="fixedBodyStyle" ref="fixedBody" @mousewheel="handleFixedMousewheel" @DOMMouseScroll="handleFixedMousewheel">
<table-body
fixed="left"
:draggable="draggable"
:prefix-cls="prefixCls"
:styleObject="fixedTableStyle"
:columns="leftFixedColumns"
:data="rebuildData"
:columns-width="columnsWidth"
:obj-data="objData"></table-body>
</div>
</div>
<div :class="[prefixCls + '-fixed-right']" :style="fixedRightTableStyle" v-if="isRightFixed">
<div :class="fixedHeaderClasses" v-if="showHeader">
<table-head
fixed="right"
:prefix-cls="prefixCls"
:styleObject="fixedRightTableStyle"
:columns="rightFixedColumns"
:column-rows="columnRows"
:fixed-column-rows="rightFixedColumnRows"
:obj-data="objData"
:columns-width="columnsWidth"
:data="rebuildData"></table-head>
</div>
<div :class="[prefixCls + '-fixed-body']" :style="fixedBodyStyle" ref="fixedRightBody" @mousewheel="handleFixedMousewheel" @DOMMouseScroll="handleFixedMousewheel">
<table-body
fixed="right"
:draggable="draggable"
:prefix-cls="prefixCls"
:styleObject="fixedRightTableStyle"
:columns="rightFixedColumns"
:data="rebuildData"
:columns-width="columnsWidth"
:obj-data="objData"></table-body>
</div>
</div>
<div :class="[prefixCls + '-fixed-right-header']" :style="fixedRightHeaderStyle" v-if="isRightFixed"></div>
<div :class="[prefixCls + '-footer']" v-if="showSlotFooter" ref="footer"><slot name="footer"></slot></div>
</div>
<Spin fix size="large" v-if="loading">
<slot name="loading"></slot>
</Spin>
</div>
</template>
<script>
import tableHead from './table-head.vue';
import tableBody from './table-body.vue';
import Spin from '../spin/spin.vue';
import { oneOf, getStyle, deepCopy, getScrollBarSize } from '../../utils/assist';
import { on, off } from '../../utils/dom';
import Csv from '../../utils/csv';
import ExportCsv from './export-csv';
import Locale from '../../mixins/locale';
import elementResizeDetectorMaker from 'element-resize-detector';
import { getAllColumns, convertToRows, convertColumnOrder, getRandomStr } from './util';
const prefixCls = 'ivu-table';
let rowKey = 1;
let columnKey = 1;
export default {
name: 'Table',
mixins: [ Locale ],
components: { tableHead, tableBody, Spin },
props: {
data: {
type: Array,
default () {
return [];
}
},
columns: {
type: Array,
default () {
return [];
}
},
size: {
validator (value) {
return oneOf(value, ['small', 'large', 'default']);
},
default () {
return !this.$IVIEW || this.$IVIEW.size === '' ? 'default' : this.$IVIEW.size;
}
},
width: {
type: [Number, String]
},
height: {
type: [Number, String]
},
stripe: {
type: Boolean,
default: false
},
border: {
type: Boolean,
default: false
},
showHeader: {
type: Boolean,
default: true
},
highlightRow: {
type: Boolean,
default: false
},
rowClassName: {
type: Function,
default () {
return '';
}
},
context: {
type: Object
},
noDataText: {
type: String
},
noFilteredDataText: {
type: String
},
disabledHover: {
type: Boolean
},
loading: {
type: Boolean,
default: false
},
draggable: {
type: Boolean,
default: false
}
},
data () {
const colsWithId = this.makeColumnsId(this.columns);
return {
ready: false,
tableWidth: 0,
columnsWidth: {},
prefixCls: prefixCls,
compiledUids: [],
objData: this.makeObjData(), // checkbox or highlight-row
rebuildData: [], // for sort or filter
cloneColumns: this.makeColumns(colsWithId),
columnRows: this.makeColumnRows(false, colsWithId),
leftFixedColumnRows: this.makeColumnRows('left', colsWithId),
rightFixedColumnRows: this.makeColumnRows('right', colsWithId),
allColumns: getAllColumns(colsWithId), // for multiple table-head, get columns that have no children
showSlotHeader: true,
showSlotFooter: true,
bodyHeight: 0,
scrollBarWidth: getScrollBarSize(),
currentContext: this.context,
cloneData: deepCopy(this.data), // when Cell has a button to delete row data, clickCurrentRow will throw an error, so clone a data
showVerticalScrollBar:false,
showHorizontalScrollBar:false,
headerWidth:0,
headerHeight:0,
};
},
computed: {
localeNoDataText () {
if (this.noDataText === undefined) {
return this.t('i.table.noDataText');
} else {
return this.noDataText;
}
},
localeNoFilteredDataText () {
if (this.noFilteredDataText === undefined) {
return this.t('i.table.noFilteredDataText');
} else {
return this.noFilteredDataText;
}
},
wrapClasses () {
return [
`${prefixCls}-wrapper`,
{
[`${prefixCls}-hide`]: !this.ready,
[`${prefixCls}-with-header`]: this.showSlotHeader,
[`${prefixCls}-with-footer`]: this.showSlotFooter
}
];
},
classes () {
return [
`${prefixCls}`,
{
[`${prefixCls}-${this.size}`]: !!this.size,
[`${prefixCls}-border`]: this.border,
[`${prefixCls}-stripe`]: this.stripe,
[`${prefixCls}-with-fixed-top`]: !!this.height
}
];
},
fixedHeaderClasses () {
return [
`${prefixCls}-fixed-header`,
{
[`${prefixCls}-fixed-header-with-empty`]: !this.rebuildData.length
}
];
},
styles () {
let style = {};
if (this.height) {
const height = parseInt(this.height);
style.height = `${height}px`;
}
if (this.width) style.width = `${this.width}px`;
return style;
},
tableStyle () {
let style = {};
if (this.tableWidth !== 0) {
let width = '';
if (this.bodyHeight === 0) {
width = this.tableWidth;
} else {
width = this.tableWidth - (this.showVerticalScrollBar?this.scrollBarWidth:0);
}
// const width = this.bodyHeight === 0 ? this.tableWidth : this.tableWidth - this.scrollBarWidth;
style.width = `${width}px`;
}
return style;
},
tableHeaderStyle () {
let style = {};
if (this.tableWidth !== 0) {
let width = '';
width = this.tableWidth;
style.width = `${width}px`;
}
return style;
},
fixedTableStyle () {
let style = {};
let width = 0;
this.leftFixedColumns.forEach((col) => {
if (col.fixed && col.fixed === 'left') width += col._width;
});
style.width = `${width}px`;
return style;
},
fixedRightTableStyle () {
let style = {};
let width = 0;
this.rightFixedColumns.forEach((col) => {
if (col.fixed && col.fixed === 'right') width += col._width;
});
//width += this.scrollBarWidth;
style.width = `${width}px`;
style.right = `${this.showVerticalScrollBar?this.scrollBarWidth:0}px`;
return style;
},
fixedRightHeaderStyle () {
let style = {};
let width = 0;
let height = this.headerHeight+1;
if(this.showVerticalScrollBar){
width = this.scrollBarWidth;
}
style.width = `${width}px`;
style.height = `${height}px`;
return style;
},
bodyStyle () {
let style = {};
if (this.bodyHeight !== 0) {
const height = this.bodyHeight;
style.height = `${height}px`;
}
return style;
},
fixedBodyStyle () {
let style = {};
if (this.bodyHeight !== 0) {
let height = this.bodyHeight - (this.showHorizontalScrollBar?this.scrollBarWidth:0);
style.height = this.showHorizontalScrollBar ? `${height}px` : `${height - 1}px`;
}
return style;
},
leftFixedColumns () {
return convertColumnOrder(this.cloneColumns, 'left');
},
rightFixedColumns () {
return convertColumnOrder(this.cloneColumns, 'right');
},
isLeftFixed () {
return this.columns.some(col => col.fixed && col.fixed === 'left');
},
isRightFixed () {
return this.columns.some(col => col.fixed && col.fixed === 'right');
}
},
methods: {
rowClsName (index) {
return this.rowClassName(this.data[index], index);
},
handleResize () {
//let tableWidth = parseInt(getStyle(this.$el, 'width')) - 1;
let tableWidth = this.$el.offsetWidth - 1;
let columnsWidth = {};
let sumMinWidth = 0;
let hasWidthColumns = [];
let noWidthColumns = [];
let maxWidthColumns = [];
let noMaxWidthColumns = [];
this.cloneColumns.forEach((col) => {
if (col.width) {
hasWidthColumns.push(col);
}
else{
noWidthColumns.push(col);
if (col.minWidth) {
sumMinWidth += col.minWidth;
}
if (col.maxWidth) {
maxWidthColumns.push(col);
}
else {
noMaxWidthColumns.push(col);
}
}
col._width = null;
});
let unUsableWidth = hasWidthColumns.map(cell => cell.width).reduce((a, b) => a + b, 0);
let usableWidth = tableWidth - unUsableWidth - sumMinWidth - (this.showVerticalScrollBar?this.scrollBarWidth:0) - 1;
let usableLength = noWidthColumns.length;
let columnWidth = 0;
if(usableWidth > 0 && usableLength > 0){
columnWidth = parseInt(usableWidth / usableLength);
}
for (let i = 0; i < this.cloneColumns.length; i++) {
const column = this.cloneColumns[i];
let width = columnWidth + (column.minWidth?column.minWidth:0);
if(column.width){
width = column.width;
}
else{
if (column._width) {
width = column._width;
}
else {
if (column.minWidth > width){
width = column.minWidth;
}
else if (column.maxWidth < width){
width = column.maxWidth;
}
if (usableWidth>0) {
usableWidth -= width - (column.minWidth?column.minWidth:0);
usableLength--;
if (usableLength > 0) {
columnWidth = parseInt(usableWidth / usableLength);
}
else {
columnWidth = 0;
}
}
else{
columnWidth = 0;
}
}
}
column._width = width;
columnsWidth[column._index] = {
width: width
};
}
if(usableWidth>0) {
usableLength = noMaxWidthColumns.length;
columnWidth = parseInt(usableWidth / usableLength);
for (let i = 0; i < noMaxWidthColumns.length; i++) {
const column = noMaxWidthColumns[i];
let width = column._width + columnWidth;
if (usableLength > 1) {
usableLength--;
usableWidth -= columnWidth;
columnWidth = parseInt(usableWidth / usableLength);
}
else {
columnWidth = 0;
}
column._width = width;
columnsWidth[column._index] = {
width: width
};
}
}
this.tableWidth = this.cloneColumns.map(cell => cell._width).reduce((a, b) => a + b, 0) + (this.showVerticalScrollBar?this.scrollBarWidth:0) + 1;
this.columnsWidth = columnsWidth;
this.fixedHeader();
},
handleMouseIn (_index) {
if (this.disabledHover) return;
if (this.objData[_index]._isHover) return;
this.objData[_index]._isHover = true;
},
handleMouseOut (_index) {
if (this.disabledHover) return;
this.objData[_index]._isHover = false;
},
// 通用处理 highlightCurrentRow 和 clearCurrentRow
handleCurrentRow (type, _index) {
let oldIndex = -1;
for (let i in this.objData) {
if (this.objData[i]._isHighlight) {
oldIndex = parseInt(i);
this.objData[i]._isHighlight = false;
}
}
if (type === 'highlight') this.objData[_index]._isHighlight = true;
const oldData = oldIndex < 0 ? null : JSON.parse(JSON.stringify(this.cloneData[oldIndex]));
const newData = type === 'highlight' ? JSON.parse(JSON.stringify(this.cloneData[_index])) : null;
this.$emit('on-current-change', newData, oldData);
},
highlightCurrentRow (_index) {
if (!this.highlightRow || this.objData[_index]._isHighlight) return;
this.handleCurrentRow('highlight', _index);
},
clearCurrentRow () {
if (!this.highlightRow) return;
this.handleCurrentRow('clear');
},
clickCurrentRow (_index) {
this.highlightCurrentRow (_index);
this.$emit('on-row-click', JSON.parse(JSON.stringify(this.cloneData[_index])), _index);
},
dblclickCurrentRow (_index) {
this.highlightCurrentRow (_index);
this.$emit('on-row-dblclick', JSON.parse(JSON.stringify(this.cloneData[_index])), _index);
},
getSelection () {
let selectionIndexes = [];
for (let i in this.objData) {
if (this.objData[i]._isChecked) selectionIndexes.push(parseInt(i));
}
return JSON.parse(JSON.stringify(this.data.filter((data, index) => selectionIndexes.indexOf(index) > -1)));
},
toggleSelect (_index) {
let data = {};
for (let i in this.objData) {
if (parseInt(i) === _index) {
data = this.objData[i];
break;
}
}
const status = !data._isChecked;
this.objData[_index]._isChecked = status;
const selection = this.getSelection();
this.$emit(status ? 'on-select' : 'on-select-cancel', selection, JSON.parse(JSON.stringify(this.data[_index])));
this.$emit('on-selection-change', selection);
},
toggleExpand (_index) {
let data = {};
for (let i in this.objData) {
if (parseInt(i) === _index) {
data = this.objData[i];
break;
}
}
const status = !data._isExpanded;
this.objData[_index]._isExpanded = status;
this.$emit('on-expand', JSON.parse(JSON.stringify(this.cloneData[_index])), status);
if(this.height){
this.$nextTick(()=>this.fixedBody());
}
},
selectAll (status) {
// this.rebuildData.forEach((data) => {
// if(this.objData[data._index]._isDisabled){
// this.objData[data._index]._isChecked = false;
// }else{
// this.objData[data._index]._isChecked = status;
// }
// });
for(const data of this.rebuildData){
if(this.objData[data._index]._isDisabled){
continue;
}else{
this.objData[data._index]._isChecked = status;
}
}
const selection = this.getSelection();
if (status) {
this.$emit('on-select-all', selection);
} else {
this.$emit('on-select-all-cancel', selection);
}
this.$emit('on-selection-change', selection);
},
fixedHeader () {
if (this.height) {
this.$nextTick(() => {
const titleHeight = parseInt(getStyle(this.$refs.title, 'height')) || 0;
const headerHeight = parseInt(getStyle(this.$refs.header, 'height')) || 0;
const footerHeight = parseInt(getStyle(this.$refs.footer, 'height')) || 0;
this.bodyHeight = this.height - titleHeight - headerHeight - footerHeight;
this.$nextTick(()=>this.fixedBody());
});
} else {
this.bodyHeight = 0;
this.$nextTick(()=>this.fixedBody());
}
},
fixedBody (){
if (this.$refs.header) {
this.headerWidth = this.$refs.header.children[0].offsetWidth;
this.headerHeight = this.$refs.header.children[0].offsetHeight;
//this.showHorizontalScrollBar = this.headerWidth>this.$refs.header.offsetWidth;
}
if (!this.$refs.tbody || !this.data || this.data.length === 0) {
this.showVerticalScrollBar = false;
}
else{
let bodyContentEl = this.$refs.tbody.$el;
let bodyEl = bodyContentEl.parentElement;
let bodyContentHeight = bodyContentEl.offsetHeight;
let bodyHeight = bodyEl.offsetHeight;
this.showHorizontalScrollBar = bodyEl.offsetWidth < bodyContentEl.offsetWidth + (this.showVerticalScrollBar?this.scrollBarWidth:0);
this.showVerticalScrollBar = this.bodyHeight? bodyHeight - (this.showHorizontalScrollBar?this.scrollBarWidth:0) < bodyContentHeight : false;
if(this.showVerticalScrollBar){
bodyEl.classList.add(this.prefixCls +'-overflowY');
}else{
bodyEl.classList.remove(this.prefixCls +'-overflowY');
}
if(this.showHorizontalScrollBar){
bodyEl.classList.add(this.prefixCls +'-overflowX');
}else{
bodyEl.classList.remove(this.prefixCls +'-overflowX');
}
}
},
hideColumnFilter () {
this.cloneColumns.forEach((col) => col._filterVisible = false);
},
handleBodyScroll (event) {
if (this.showHeader) this.$refs.header.scrollLeft = event.target.scrollLeft;
if (this.isLeftFixed) this.$refs.fixedBody.scrollTop = event.target.scrollTop;
if (this.isRightFixed) this.$refs.fixedRightBody.scrollTop = event.target.scrollTop;
this.hideColumnFilter();
},
handleFixedMousewheel(event) {
let deltaY = event.deltaY;
if(!deltaY && event.detail){
deltaY = event.detail * 40;
}
if(!deltaY && event.wheelDeltaY){
deltaY = -event.wheelDeltaY;
}
if(!deltaY && event.wheelDelta){
deltaY = -event.wheelDelta;
}
if(!deltaY) return;
const body = this.$refs.body;
const currentScrollTop = body.scrollTop;
if (deltaY < 0 && currentScrollTop !== 0) {
event.preventDefault();
}
if (deltaY > 0 && body.scrollHeight - body.clientHeight > currentScrollTop) {
event.preventDefault();
}
//body.scrollTop += deltaY;
let step = 0;
let timeId = setInterval(()=>{
step += 5;
if(deltaY>0){
body.scrollTop += 2;
}
else{
body.scrollTop -= 2;
}
if(step >= Math.abs(deltaY)){
clearInterval(timeId);
}
}, 5);
},
handleMouseWheel (event) {
const deltaX = event.deltaX;
const $body = this.$refs.body;
if (deltaX > 0) {
$body.scrollLeft = $body.scrollLeft + 10;
} else {
$body.scrollLeft = $body.scrollLeft - 10;
}
},
sortData (data, type, index) {
const key = this.cloneColumns[index].key;
data.sort((a, b) => {
if (this.cloneColumns[index].sortMethod) {
return this.cloneColumns[index].sortMethod(a[key], b[key], type);
} else {
if (type === 'asc') {
return a[key] > b[key] ? 1 : -1;
} else if (type === 'desc') {
return a[key] < b[key] ? 1 : -1;
}
}
});
return data;
},
handleSort (_index, type) {
const index = this.GetOriginalIndex(_index);
this.cloneColumns.forEach((col) => col._sortType = 'normal');
const key = this.cloneColumns[index].key;
if (this.cloneColumns[index].sortable !== 'custom') { // custom is for remote sort
if (type === 'normal') {
this.rebuildData = this.makeDataWithFilter();
} else {
this.rebuildData = this.sortData(this.rebuildData, type, index);
}
}
this.cloneColumns[index]._sortType = type;
this.$emit('on-sort-change', {
column: JSON.parse(JSON.stringify(this.allColumns[this.cloneColumns[index]._index])),
key: key,
order: type
});
},
handleFilterHide (index) { // clear checked that not filter now
if (!this.cloneColumns[index]._isFiltered) this.cloneColumns[index]._filterChecked = [];
},
filterData (data, column) {
return data.filter((row) => {
//如果定义了远程过滤方法则忽略此方法
if (typeof column.filterRemote === 'function') return true;
let status = !column._filterChecked.length;
for (let i = 0; i < column._filterChecked.length; i++) {
status = column.filterMethod(column._filterChecked[i], row);
if (status) break;
}
return status;
});
},
filterOtherData (data, index) {
let column = this.cloneColumns[index];
if (typeof column.filterRemote === 'function') {
column.filterRemote.call(this.$parent, column._filterChecked, column.key, column);
}
this.cloneColumns.forEach((col, colIndex) => {
if (colIndex !== index) {
data = this.filterData(data, col);
}
});
return data;
},
handleFilter (index) {
const column = this.cloneColumns[index];
let filterData = this.makeDataWithSort();
// filter others first, after filter this column
filterData = this.filterOtherData(filterData, index);
this.rebuildData = this.filterData(filterData, column);
this.cloneColumns[index]._isFiltered = true;
this.cloneColumns[index]._filterVisible = false;
this.$emit('on-filter-change', column);
},
/**
* #2832
* 应该区分当前表头的 column 是左固定还是右固定
* 否则执行到 $parent 时,方法的 index 与 cloneColumns 的 index 是不对应的
* 左固定和右固定,要区分对待
* 所以,此方法用来获取正确的 index
* */
GetOriginalIndex (_index) {
return this.cloneColumns.findIndex(item => item._index === _index);
},
handleFilterSelect (_index, value) {
const index = this.GetOriginalIndex(_index);
this.cloneColumns[index]._filterChecked = [value];
this.handleFilter(index);
},
handleFilterReset (_index) {
const index = this.GetOriginalIndex(_index);
this.cloneColumns[index]._isFiltered = false;
this.cloneColumns[index]._filterVisible = false;
this.cloneColumns[index]._filterChecked = [];
let filterData = this.makeDataWithSort();
filterData = this.filterOtherData(filterData, index);
this.rebuildData = filterData;
this.$emit('on-filter-change', this.cloneColumns[index]);
},
makeData () {
let data = deepCopy(this.data);
data.forEach((row, index) => {
row._index = index;
row._rowKey = rowKey++;
});
return data;
},
makeDataWithSort () {
let data = this.makeData();
let sortType = 'normal';
let sortIndex = -1;
let isCustom = false;
for (let i = 0; i < this.cloneColumns.length; i++) {
if (this.cloneColumns[i]._sortType !== 'normal') {
sortType = this.cloneColumns[i]._sortType;
sortIndex = i;
isCustom = this.cloneColumns[i].sortable === 'custom';
break;
}
}
if (sortType !== 'normal' && !isCustom) data = this.sortData(data, sortType, sortIndex);
return data;
},
makeDataWithFilter () {
let data = this.makeData();
this.cloneColumns.forEach(col => data = this.filterData(data, col));
return data;
},
makeDataWithSortAndFilter () {
let data = this.makeDataWithSort();
this.cloneColumns.forEach(col => data = this.filterData(data, col));
return data;
},
makeObjData () {
let data = {};
this.data.forEach((row, index) => {
const newRow = deepCopy(row);// todo 直接替换
newRow._isHover = false;
if (newRow._disabled) {
newRow._isDisabled = newRow._disabled;
} else {
newRow._isDisabled = false;
}
if (newRow._checked) {
newRow._isChecked = newRow._checked;
} else {
newRow._isChecked = false;
}
if (newRow._expanded) {
newRow._isExpanded = newRow._expanded;
} else {
newRow._isExpanded = false;
}
if (newRow._highlight) {
newRow._isHighlight = newRow._highlight;
} else {
newRow._isHighlight = false;
}
data[index] = newRow;
});
return data;
},
// 修改列,设置一个隐藏的 id,便于后面的多级表头寻找对应的列,否则找不到
makeColumnsId (columns) {
return columns.map(item => {
if ('children' in item) item.children = this.makeColumnsId(item.children);
item.__id = getRandomStr(6);
return item;
});
},
makeColumns (cols) {
// 在 data 时,this.allColumns 暂时为 undefined
let columns = deepCopy(getAllColumns(cols));
let left = [];
let right = [];
let center = [];
columns.forEach((column, index) => {
column._index = index;
column._columnKey = columnKey++;
column._width = column.width ? column.width : ''; // update in handleResize()
column._sortType = 'normal';
column._filterVisible = false;
column._isFiltered = false;
column._filterChecked = [];
if ('filterMultiple' in column) {
column._filterMultiple = column.filterMultiple;
} else {
column._filterMultiple = true;
}
if ('filteredValue' in column) {
column._filterChecked = column.filteredValue;
column._isFiltered = true;
}
if ('sortType' in column) {
column._sortType = column.sortType;
}
if (column.fixed && column.fixed === 'left') {
left.push(column);
} else if (column.fixed && column.fixed === 'right') {
right.push(column);
} else {
center.push(column);
}
});
return left.concat(center).concat(right);
},
// create a multiple table-head
makeColumnRows (fixedType, cols) {
return convertToRows(cols, fixedType);
},
exportCsv (params) {
if (params.filename) {
if (params.filename.indexOf('.csv') === -1) {
params.filename += '.csv';
}
} else {
params.filename = 'table.csv';
}
let columns = [];
let datas = [];
if (params.columns && params.data) {
columns = params.columns;
datas = params.data;
} else {
columns = this.allColumns;
if (!('original' in params)) params.original = true;
datas = params.original ? this.data : this.rebuildData;
}
let noHeader = false;
if ('noHeader' in params) noHeader = params.noHeader;
const data = Csv(columns, datas, params, noHeader);
if (params.callback) params.callback(data);
else ExportCsv.download(params.filename, data);
},
dragAndDrop(a,b) {
this.$emit('on-drag-drop', a,b);
}
},
created () {
if (!this.context) this.currentContext = this.$parent;
this.showSlotHeader = this.$slots.header !== undefined;
this.showSlotFooter = this.$slots.footer !== undefined;
this.rebuildData = this.makeDataWithSortAndFilter();
},
mounted () {
this.handleResize();
this.$nextTick(() => this.ready = true);
on(window, 'resize', this.handleResize);
this.observer = elementResizeDetectorMaker();
this.observer.listenTo(this.$el, this.handleResize);
this.$on('on-visible-change', (val) => {
if (val) {
this.handleResize();
}
});
},
beforeDestroy () {
off(window, 'resize', this.handleResize);
this.observer.removeListener(this.$el, this.handleResize);
},
watch: {
data: {
handler () {
const oldDataLen = this.rebuildData.length;
this.objData = this.makeObjData();
this.rebuildData = this.makeDataWithSortAndFilter();
this.handleResize();
if (!oldDataLen) {
this.fixedHeader();
}
// here will trigger before clickCurrentRow, so use async
setTimeout(() => {
this.cloneData = deepCopy(this.data);
}, 0);
},
deep: true
},
columns: {
handler () {
// todo 这里有性能问题,可能是左右固定计算属性影响的
const colsWithId = this.makeColumnsId(this.columns);
this.allColumns = getAllColumns(colsWithId);
this.cloneColumns = this.makeColumns(colsWithId);
this.columnRows = this.makeColumnRows(false, colsWithId);
this.leftFixedColumnRows = this.makeColumnRows('left', colsWithId);
this.rightFixedColumnRows = this.makeColumnRows('right', colsWithId);
this.rebuildData = this.makeDataWithSortAndFilter();
this.handleResize();
},
deep: true
},
height () {
this.handleResize();
},
showHorizontalScrollBar () {
this.handleResize();
},
showVerticalScrollBar () {
this.handleResize();
}
}
};
</script>