vue-table.vue 15.6 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
/**
* @file
* @author 何文林
* @date 2017/9/20
*/
<template>
	<div id="tableComponent" ref="tableScroll">
		<!--内容 -->
		<div class="content">
			<!--左边固定-->
			<div class="table-fixed-left"
					 v-if="showSelect && selectFixed">
				<div class="table-header"
						 :style="titleFixed == 'fixed' ? {position: 'absolute', overflow:'hidden', zIndex: 1}: {}">
					<table cellpadding="0px" cellspacing="0px" style="width: 50px;">
						<colgroup>
							<col style="width: 50px; min-width: 50px;"/>
						</colgroup>
						<thead>
						<tr :style="{height: titleHeight + 'px', borderBottom: (titleFixed=='auto') ? 0 :
							'1px solid #ddd'}">
							<th>
								<label for="allSelect" class="selectLable" @click="checkedAllItem">
									<check-box :isTrue="checkedAll"></check-box>
								</label>
							</th>
						</tr>
						</thead>
					</table>
				</div>
				<div class="table-body"
						 :style="titleFixed == 'fixed' ? {paddingTop: titleHeight + 'px', overflow: 'hidden', height: scrollHight + 'px'} : ''">
					<table cellpadding="0px" cellspacing="0px" style="width: 50px;" ref="tFixedLeft">
						<colgroup>
							<col style="width: 50px; min-width: 50px;"/>
						</colgroup>
						<tbody>
						<tr v-for="(item, index) in tdata"
								@mouseenter="mouseEnter(index)"
								@mouseout="mouseOut(index)"
								:class="toTrClass(index)"
								:style="{height: tdHeight + 'px'}">
							<td>
								<label :for="'left1' + index" class="selectLable">
									<input :id="'left1' + index"
												 type="checkbox"
												 :value="index" v-model="checkedItem"
												 :disabled="isDisAbled(index)">
									<check-box :isTrue="(checkedItem.indexOf(index) > -1)"></check-box>
								</label>
							</td>
						</tr>
						</tbody>
					</table>
				</div>
			</div>
			<!--中间滚动内容-->
			<div class="table-scroll"
					 ref="cScroll"
					 :style="titleFixed == 'fixed' ? {overflow: 'auto', height: scrollHight + 'px'} : {}">
				<div class="table-header"
						 :style="titleFixed == 'fixed' ? {width: tableContentWith + 'px', position: 'absolute',overflow:'hidden'}: {}">
					<table class="scroll-header" :style="{width: setWithd}" ref="cHead">
						<colgroup>
							<col v-if="showSelect" style="width: 50px; min-width: 50px"/>
							<col v-for="item in tcolumns" :style="{width: item.width+'px', minWidth: item.width + 'px'}"/>
							<col v-if="showHandle" style="width: 150px; min-width: 150px"/>
						</colgroup>
						<thead>
						<tr :style="{height: titleHeight + 'px', borderBottom: (titleFixed=='auto') ? 0 :
						'1px solid #ddd'}">
							<th v-if="showSelect">
								<label for="allSelect" class="selectLable" @click="checkedAllItem">
									<check-box :isTrue="checkedAll"></check-box>
								</label>
							</th>
							<th v-for="item in tcolumns">{{item.title}}</th>
							<th v-if="showHandle">操作</th>
						</tr>
						</thead>
					</table>
				</div>
				<div class="table-body" :style="titleFixed == 'fixed' ? {paddingTop: titleHeight + 'px'} : ''">
					<table :style="{width: setWithd}">
						<colgroup>
							<col v-if="showSelect" style="width: 50px; min-width: 50px"/>
							<col v-for="item in tcolumns" :style="{width: item.width+'px', minWidth: item.width + 'px'}"/>
							<col v-if="showHandle" style="width: 150px; min-width: 150px"/>
						</colgroup>
						<tbody>
						<tr v-for="(dataItem, index) in tdata"
								@mouseenter.stop.prevent="mouseEnter(index)"
								@mouseout.stop.prevent="mouseOut(index)"
								v-on:click.stop="tItamClick(dataItem)"
								:class="toTrClass(index)"
								:style="{height: tdHeight + 'px'}"
						>
							<td v-if="showSelect" class="tbSelect">
								<label :for="'left1' + index" class="selectLable">
									<input :id="'left1' + index" type="checkbox"
												 :value="index" v-model="checkedItem"
												 :disabled="isDisAbled(index)">
									<check-box :isTrue="(checkedItem.indexOf(index) > -1)"></check-box>
								</label>
							</td>
							<!--<td v-for="item in tcolumns"-->
									<!--:class="'text' + item.textAlign"-->
									<!--@mouseup="selectText(item.selectText, dataItem[item.key])"-->
									<!--v-ellipsis="dataItem[item.key] + ',' +item.textLine">{{dataItem[item.key]}}-->
							<!--</td>-->
							<td v-for="item in tcolumns"
									:class="'text' + item.textAlign"
									v-ellipsis="dataItem[item.key] + ',' +item.textLine">{{dataItem[item.key]}}
							</td>
							<td :class="isDisAbled(index) ? 'textDisable' : ''"
									v-if="showHandle" class="handleAction">
								<slot name="operations" :item="dataItem">
									<span>编辑</span>
									<span>删除</span>
									<span>禁用1</span>
								</slot>
							</td>
						</tr>
						</tbody>
					</table>
				</div>
			</div>
			<!--右边固定-->
			<div class="table-fixed-right"
					 v-if="showHandle && handleFixed">
				<div class="table-header"
						 :style="titleFixed == 'fixed' ? {width: tableContentWith + 'px', position: 'absolute',overflow:'hidden'}: {}">
					<table>
						<colgroup>
							<col style="width: 150px"/>
						</colgroup>
						<thead>
						<tr :style="{height: titleHeight + 'px', borderBottom: (titleFixed=='auto') ? 0 :
							'1px solid #ddd'}">
							<th>操作</th>
						</tr>
						</thead>
					</table>
				</div>
				<div class="table-body"
						 :style="titleFixed == 'fixed' ? {paddingTop: titleHeight + 'px', overflow: 'hidden', height: scrollHight + 'px'} : ''">
					<table ref="tFixedRight">
						<colgroup>
							<col style="width: 150px"/>
						</colgroup>
						<tbody>
						<tr v-for="(item, index) in tdata"
								@mouseenter="mouseEnter(index)"
								@mouseout="mouseOut(index)"
								:class="toTrClass(index)"
								:style="{height: tdHeight + 'px'}"
						>
							<td :class="isDisAbled(index) ? 'textDisable' : ''" class="handleAction">
								<slot name="operations" :item="item">
									<span>编辑</span>
									<span>删除</span>
									<span>禁用1</span>
								</slot>
							</td>
						</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>
		<!--分页-->
		<div class="page" v-if="page.totalPage">
			<pagination :total-page="page.totalPage"
									:size="'md'"
									v-model="currentPage"
									@change="changePage"
									:max-size="page.maxSize"></pagination>
		</div>
		<!--划词提示框-->
		<!--<p class="crossWord">{{crossWord}}</p>-->
	</div>
</template>

<script>
  import Pagination from './vue-page.vue'
  import checkBox from './checkbox.vue'
  export default{
    components: {
      Pagination,
      checkBox
    },
    props: {
      tcolumns: {
        type: Array,
        default: []
      },
      tdata: {
        type: Array,
        default: []
      },
      // 显示选择空间
      showSelect: {
        type: Boolean,
        default: false
      },
      // 显示操作列表
      showHandle: {
        type: Boolean,
        default: false
      },
      // 头部是否固定
      titleFixed: {
        type: String,
        default: 'auto'
      },
      titleHeight: {
        type: Number,
        default: 32
      },
      tdHeight: {
        type: Number,
        default: 50
      },
      scrollHight: {
        type: Number,
        default: 400
      },
      selectFixed: {
        type: Boolean,
        default: false
      },
      handleFixed: {
        type: Boolean,
        default: false
      },
      page: {
        type: Object,
        default: function () {
          return {}
        }
      }
    },
    data() {
      return {
        hoverIndex: -1,
        checkedItem: [],
        checkedAll: false,
        setWithd: '1000px',
        currentPage: 1,
        // 宽度配置
        checkBoxWidth: 50,
        tableContentWith: 600,
        handleWith: 150,
        crossWord: ''
      }
    },
    directives: {
      // 行数溢出省略号指令
      ellipsis: {
        bind(el, binding) {
          let line = 2
          if (binding.value) {
            let val = (
              binding.value).split(',')
            line = val[1]
          }
          setTimeout(() => {
            let max = el.offsetWidth
            max = max * line
            let text = (
              binding.value).trim().replace(' ', ' ') //for fix white-space bug
            let ellipsisChar = '...'
            let clone = el.cloneNode(true)
            clone.style.visibility = 'hidden'
            clone.style.whiteSpace = 'nowrap'
            clone.style.width = 'auto'
            document.body.appendChild(clone)
            let width = clone.offsetWidth
            if (width > max) {
              let stop = Math.floor(text.length * max / width)
              let tempStr = text.substring(0, stop) + ellipsisChar
              clone.innerHTML = tempStr
              width = clone.offsetWidth
              if (width > max) {
                while (width > max && stop > 1) {
                  stop--
                  tempStr = text.substring(0, (
                    stop - 5)) + ellipsisChar
                  clone.innerHTML = tempStr
                  width = clone.offsetWidth
                }
              } else if (width < max) {
                while (width < max && stop < text.length) {
                  stop++
                  tempStr = text.substring(0, stop) + ellipsisChar
                  clone.innerHTML = tempStr
                  width = clone.offsetWidth
                }
                if (width > max) {
                  tempStr = text.substring(0, stop - 1) + ellipsisChar
                }
              }
              el.innerHTML = tempStr
            }
            document.body.removeChild(clone)
          }, 0)
        }
      }
    },
    methods: {
      mouseEnter(index) {
        this.hoverIndex = index
      },
      mouseOut(e) {
        this.hoverIndex = -1
      },
      // 鼠标点击一行
      tItamClick(item) {
        if (item.disable) {
          return
        }
        this.$emit('clickItem', item)
      },
      // 鼠标滑过 class
      toTrClass(index) {
        if (this.tdata[index] && this.tdata[index].disable) {
          return 'trDisable'
        }
        if (this.hoverIndex === index) {
          return 'mouseover'
        } else {
          return ''
        }
      },
      // 表格初始化宽度
      initTableWidth() {
        const tableScroll = this.$refs.tableScroll
        let AllWidth = 0
        if (!this.showSelect) {
          this.checkBoxWidth = 0
        } else {
          AllWidth += 50
        }
        if (!this.showHandle) {
          this.handleWith = 0
        } else {
          AllWidth += 150
        }
        // this.tableContentWith = tableScroll.offsetWidth - this.checkBoxWidth - this.handleWith
        this.tableContentWith = tableScroll.offsetWidth
        this.tcolumns.forEach(item => {
          AllWidth += item.width
        })
        if (AllWidth > tableScroll.offsetWidth) {
          this.setWithd = AllWidth + 'px'
        } else {
          this.setWithd = '100%'
        }
      },
      // 判断是否可用
      isDisAbled(index) {
        return this.tdata[index] ? this.tdata[index].disable : false
      },
      // 分页变动
      changePage(page) {
        this.$emit('changePage', page)
      },
      // 全选或者全不选
      isAllSelect (isSelect) {
        const _this = this
        if (this.tdata.length === 0) {
          return
        }
        if (isSelect) {
          this.tdata.forEach((item, index) => {
            if (!item.disable && (
              this.checkedItem.indexOf(index) < 0)) {
              _this.checkedItem.push(index)
            }
          })
        } else {
          _this.checkedItem = []
        }
      },
      // 全选操作
      checkedAllItem () {
        this.checkedAll = !this.checkedAll
        this.isAllSelect(this.checkedAll)
      },
      // 划词提示
      selectText(isSelect) {
        if (isSelect) {
          let txt = ''
          if (document.selection) {
            txt = document.selection.createRange().text
          } else {
            txt = window.getSelection() + ''
          }
          console.log(txt)
        }
      },
      // 滚动表格
      scrollTable (e) {
        const _this = this
        let timer = null
        clearInterval(timer)
        timer = setTimeout(() => {
          if (this.titleFixed === 'fixed') {
            _this.$refs.cHead.style.transform = 'translateZ(0.01px)'
            _this.$refs.cHead.style.transform = 'translateX(' + -(e.target.scrollLeft) + 'px)'
            if (_this.selectFixed) {
              _this.$refs.tFixedLeft.style.transform = 'translateY(' + -(e.target.scrollTop) + 'px)'
            }
            if (_this.handleFixed) {
              _this.$refs.tFixedRight.style.transform = 'translateY(' + -(e.target.scrollTop) + 'px)'
            }
          }
        }, 10)
      }
    },
    mounted() {
      if (this.$refs.tableScroll) {
        this.initTableWidth()
        window.addEventListener('resize', this.initTableWidth)
      } else {
        window.removeEventListener('resize', this.initTableWidth)
      }
      this.$refs.cScroll.addEventListener('scroll', this.scrollTable)
    },
    destroyed() {
      window.removeEventListener('resize', this.initTableWidth)
    },
    watch: {
      checkedItem: function (val) {
        let arr = this.tdata
        let num = 0
        arr.forEach((item, index) => {
          if (!item.disable) {
            num += 1
          }
        })
        if (val.length !== num) {
          this.checkedAll = false
        } else {
          this.checkedAll = true
        }
        this.$emit('selectCheck', val)
      }
    }
  }
</script>

<style lang="less" scoped>
	* {
		margin: 0;
		padding: 0;
	}

	table {
		border-collapse: collapse;
		tr {
			box-sizing: border-box;
			overflow: hidden;
			border-right: 1px solid #ddd;
			border-bottom: 1px solid #ddd;
		}
		tr:nth-of-type(2n) {
			td {
				background: #fafafa;
			}
		}
		tr:nth-of-type(2n + 1) {
			td {
				background: #fff;
			}
		}
	}

	td, th {
		border: 1px solid #ddd;
		box-sizing: border-box;
	}

	th {
		border-bottom: 0;
		text-align: center;
		background: #fafafa;
	}

	td {
		overflow: hidden;
		img {
			width: 36px;
			height: 36px;
		}
	}

	#tableComponent {
		width: 100%;
		overflow: hidden;
		position: relative;
		font-size: 14px;
	}

	.selectLable {
		i {
			font-size: 18px;
		}
		input {
			display: none;
		}
		& > div {
			justify-content: center;
		}
	}

	.titleHeight {
		background: #fafafa;
	}

	.content {
		position: relative;
		overflow: hidden;
	}

	.table-fixed-left {
		position: absolute;
		left: 0;
		top: 0;
		z-index: 10;
		width: 50px;
		.table-header {
			z-index: 1;
		}
		td {
			text-align: center;
		}
	}

	.showSelect {
		margin-left: 50px;
	}

	.showHandle {
		margin-right: 150px;
	}

	.table-scroll {
		overflow: scroll;
		overflow-y: hidden;
		.table-header {
			z-index: 1;
		}
		.tbSelect {
			text-align: center;
		}
		td, th {
			border-right: 0;
		}
		tr.textDisable {
			color: #dddddd;
		}
	}

	.table-fixed-right {
		position: absolute;
		right: 0;
		top: 0;
		z-index: 10;
		.table-header {
			z-index: 1;
		}
		.table-body {
			background: #ffffff;
			tr:hover {
				background: red;
			}
			td {
				text-align: center;
			}
			span:hover {
				text-decoration: underline;
			}
		}
	}

	.mouseover {
		td {
			background: #ffffbb !important;
		}
	}

	.selectTr {
		td {
			background: #ffffbb;
		}
	}

	.trDisable {
		color: #ccc;
	}

	.textleft {
		text-align: left;
	}

	.textright {
		text-align: right;
	}

	.textcenter {
		text-align: center;
	}

	.page {
		display: flex;
		justify-content: flex-end;
	}

	.handleAction {
		color: #5a82be;
		text-align: center;
		span:hover {
			text-decoration: underline;
		}
	}

	.crossWord {
		position: absolute;
		left: 0;
		top: 0;
	}
</style>