需求:用element-ui渲染了一个表格,由于后端返回了大量数据并且没实现分页,需前端自行处理,所以做了一个懒加载功能,代码如下:
1,HTML
<el-table
border
ref="myTable"
style="width: 100%"
height="350"
:data="tableData"
v-loading = "isLoading"
element-loading-background = "rgba(255, 255, 255, .5)"
element-loading-text = "加载中,请稍后..."
element-loading-spinner = "el-icon-loading">
<el-table-column align="center" prop="create_node" label="行点新增"> </el-table-column>
<el-table-column align="center" prop="modify_node" label="修改形点"> </el-table-column>
<el-table-column align="center" prop="delete_node" label="删除形点"> </el-table-column>
<el-table-column align="center" prop="create_object" label="新增对象"> </el-table-column>
<el-table-column align="center" prop="modify_object" label="修改对象"> </el-table-column>
<el-table-column align="center" prop="delete_object" label="删除对象"> </el-table-column>
</el-table>
2、JS
data () {
return {
isLoading: false,
tableData: [],
oldData: [],
currentPage: 1
}
},
mounted () {
this.ListFn()
this.tableListener()
},
methods: {
// 获取列表数据
async ListFn () {
this.isLoading = true
const res = await PerfToDateStatistics(this.queryForm)
this.oldData = res.data || []
this.initData()
this.isLoading = false
},
// 数据请求完带 把数据给 this.oldData
// 之后调用 initData 获取当前数据第一次数据, 在滚动时 让currentPage + 1, 之后再 initData
initData () {
const pageSize = 10
const currentPage = this.currentPage += 1
if (pageSize * this.currentPag > this.oldData.length) return false
this.tableData = [...this.tableData, ...this.pagination(pageSize, currentPage, this.oldData)]
},
// 数据叠加处理
pagination (pageSize, currentPage, arr) {
var skipNum = (currentPage - 1) * pageSize
var newArr = (skipNum + pageSize >= arr.length) ? arr.slice(skipNum, arr.length) : arr.slice(skipNum, skipNum + pageSize)
return newArr
},
// 监听页面滚动
tableListener () {
const that = this
const dom = that.$refs.myTable.bodyWrapper
dom.addEventListener('scroll', function () {
const scrollDistance = dom.scrollHeight - dom.scrollTop - dom.clientHeight
if (scrollDistance <= 0) { // 等于0证明已经到底,可以请求接口
that.initData()
}
})
},
}