今天遇到了一个需求,就是在pc端使用滚动条进行分页处理。一开始我是打算使用v-infinite-scroll的,但是使用的是el-table,为了使滚动条和表格显得不那么突兀,所以还是使用了el-table的height属性来加载滚动条。(其实就是单纯的懒)
代码:
<el-table :row-key="getSchoolRowKeys" key="table2" :data="tableData_1" v-loading="loading1" :height="350"
v-if="radio==='3'&&type==='first'" element-loading-text="拼命加载中" stripe highlight-current-row
class="common table tb1" ref="multipleTable1" :show-summary="true"
@selection-change="handleSelectionChange" :summary-method="getSummaries"
:header-cell-class-name="cellClass" @sort-change="sortChange">
<template slot="empty">
<i :class="table_empty_img"></i>
<p class="table_empty_text">{{dataText}}</p>
</template>
<el-table-column type="selection" :reserve-selection="true" align="center" width="65">
</el-table-column>
<el-table-column property="sdate" label="交易日期" :show-overflow-tooltip="true" :resizable="false"
width="120" sortable="custom">
<template slot-scope="scope">
<span>{{scope.row.sdate|dateFormat}}</span>
</template>
</el-table-column>
</el-table>
这样做的话,第二步就是给表格滚动条添加事件监听。给滚动条添加监听事件,首先我们要先选取需要监听的dom节点。由于使用的是vue,所以直接使用ref来进行dom节点的获取。在获取到节点之后,我们通过节点拿到目标盒子可视化的高度,滚动条的位置和滚动条的高度。 如果想要做出滚动条触底刷新的效果,我们还需要进行一个判断:
scrollTop + windowHeight === scrollHeight
其中scrollTop是滚动条的滚动距离,变量windowHeight是可视区的高度,变量scrollHeight是滚动条的总高度。 scrollTop + windowHeight === scrollHeight就表示滚动条已经到底。但是一般情况下用户滚动的高度都不会很精准,所以一般滚动条触底的判断条件都会改为:
scrollTop + windowHeight + S > scrollHeight
S表示触底的距离,也就是距离底部 S px进行开发。
代码: (注意1:this.dom 需要在data中注册!!!!
注意2: this.dom = this.$refs.multipleTable1.bodyWrapper 一定要在表格的dom节点渲染完毕之后在添加该监听。重点就是像我这样目标节点使用了v-if的,一定要在v-if渲染完在使用ref,不然this.$refs是获取不到该节点的。)
scrollFu1() {
// 获取需要绑定的table
this.dom = this.$refs.multipleTable1.bodyWrapper
this.dom.addEventListener('scroll', () => {
console.log('scrollTop',this.dom.scrollTop,'clientHeight',this.dom.clientHeight,'scrollHeight',this.dom.scrollHeight);
if (this.dom.scrollTop + this.dom.clientHeight + 20 > this.dom.scrollHeight) {
// 获取到的不是全部数据 当滚动到底部 继续获取新的数据
if (this.tablePageCW1[0] <= this.tablePageCW1[2]) {
this.tablePageCW1[0] += 10;
this.loadCwUnrelatedDtls('', '', () => {
this.dom.scrollTop = this.dom.scrollTop - 100
})
}
}
})
},
最后在使用 this.dom.scrollTop = this.dom.scrollTop - 100,来控制滚动条的位置。