关键点:
1、 el-table 需要设置高度 height;
2、el-table 外层盒子需要设置一个高度,并且设置 overflow:hidden;
3、获取 el-table 的 bodyWrapper:divData
divData.scrollTop + divData.clientHeight + 1 >= divData.scrollHeight;(触底)
重新请求数据;并将列表置顶:设置 divData.scrollTop = 0;
4、为el-table 添加鼠标移入移除事件,启停滚动;
- <template>
- <div class="span-roll-table">
- <div class="table-contain">
- <el-table
- ref="rollTable"
- :data="list"
- height="100%"
- :span-method="objectSpanMethod"
- :header-cell-style="{
- textAlign: 'center',
- width: 'fit-content',
- backgroundColor: '#F2F6FC',
- }"
- class="table"
- @mouseenter.native="stopScroll"
- @mouseleave.native="startScroll"
- >
- el-table>
- div>
- div>
- template>
-
- <script>
- export default {
- data() {
- return {
- list: [],
- rollTimer: null,
- };
- },
- mounted() {
- this.startScroll();
- },
- methods: {
- // 获取新数据
- async onChange() {
- this.list = [
- {
- name: "1",
- },
- {
- name: "2",
- },
- {
- name: "3",
- },
- {
- name: "4",
- },
- ];
-
- // 将列表置顶
- this.$nextTick(() => {
- const table = this.$refs.rollTable;
- const divData = table.bodyWrapper;
- divData.scrollTop = 0;
- });
- },
- // 开始滚动
- startScroll() {
- this.tableScroll(false);
- },
- // 停止滚动
- stopScroll() {
- this.tableScroll(true);
- },
- // 列表滚动
- tableScroll(stop) {
- if (stop) {
- if (this.rollTimer) {
- clearInterval(this.rollTimer);
- return;
- }
- }
- const table = this.$refs.rollTable;
- const divData = table.bodyWrapper;
- this.rollTimer = setInterval(() => {
- divData.scrollTop += 2;
- this.$nextTick(() => {
- if (
- divData.scrollTop + divData.clientHeight + 1 >=
- divData.scrollHeight
- ) {
- this.onChange();
- }
- });
- }, 200);
- },
- // 合并列表第一个单元格(并列排名)
- objectSpanMethod({ row, column, rowIndex, columnIndex }) {
- if (columnIndex === 0) {
- // 获取当前单元格的值(单元格项一定要配置 prop 属性,否则拿不到值!!!!)
- const currentValue = row[column.property];
- // 获取上一行相同列的值
- const preRow = this.typeTableData[rowIndex - 1];
- const preValue = preRow ? preRow[column.property] : null;
- // 如果当前值和上一行的值相同,则将当前单元格隐藏
- if (currentValue === preValue) {
- return { rowspan: 0, colspan: 0 };
- } else {
- // 否则计算当前单元格应该跨越多少行
- let rowspan = 1;
- for (let i = rowIndex + 1; i < this.typeTableData.length; i++) {
- const nextRow = this.typeTableData[i];
- const nextValue = nextRow[column.property];
- if (nextValue === currentValue) {
- rowspan++;
- } else {
- break;
- }
- }
- return { rowspan, colspan: 1 };
- }
- }
- },
- },
- beforeDestroy() {
- clearInterval(this.rollTimer);
- this.startScroll = () => {};
- },
- };
- script>
- <style lang="less" scoped>
- .span-roll-table {
- height: 400px;
-
- .table-contain {
- height: 100%;
- overflow: hidden;
- }
- }
-
- /* 隐藏滚动条,但仍然可以滚动 */
- ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
- display: none; /* 针对Webkit浏览器 */
- }
- style>