表格数据量一页占不下的时候,需要定位到指定的行,显示在可视区域中。采用
scrollTo | 滚动到一组特定坐标 | (options: ScrollToOptions | number, yCoord?: number) |
核心代码
/** 滚动到指定行 tableScrollToRowtableElement:表格元素 install.refs.[tableRef]rowindex:定位到行号isprecise:是否精确计算行高,默认是false不计算,只有第一行的行高
*/
function tableScrollToRow(tableElement, rowindex, isprecise = false) {const theTableRows = tableElement.$el.querySelectorAll('.el-table__body tbody .el-table__row')let scrollTop = 0;for (let i = 0; i < theTableRows.length; i++) {if (i === rowindex) {break}scrollTop += theTableRows[i].offsetHeightif (!isprecise) {scrollTop *= (rowindex - 2);break;}}tableElement.scrollTo(0, scrollTop)
}
完整代码
<template><h2>表格的滚动条定位</h2><div><el-button type="primary" @click="goTop">gotop</el-button><el-button type="primary" @click="goEnd">goEnd</el-button></div><el-table ref="tableRef" :data="tableData" border style="width: 100%" highlight-current-row height="800"><el-table-column type="index" label="序号" width="100" /><el-table-column prop="date" label="Date" width="180" /><el-table-column prop="name" label="Name" width="180" /><el-table-column prop="address" label="Address" /></el-table>
</template><script lang="ts" setup >
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'const install = getCurrentInstance();
const tableRef = ref();
const tableData = reactive<any>([])function goTop() {// 滚动到顶部tableScrollToRow(install.refs.tableRef, 0);
}/** 滚动到指定行 tableScrollToRowtableElement:表格元素 install.refs.[tableRef]rowindex:定位到行号isprecise:是否精确计算行高,默认是false不计算,只有第一行的行高
*/
function tableScrollToRow(tableElement, rowindex, isprecise = false) {const theTableRows = tableElement.$el.querySelectorAll('.el-table__body tbody .el-table__row')let scrollTop = 0;for (let i = 0; i < theTableRows.length; i++) {if (i === rowindex) {break}scrollTop += theTableRows[i].offsetHeightif (!isprecise) {scrollTop *= (rowindex - 2);break;}}tableElement.scrollTo(0, scrollTop)
}function goEnd() {// 滚动到底部tableScrollToRow(install.refs.tableRef, tableData.length);
}onMounted(() => {for (let i = 0; i < 100; i++) {let obj = {date: '2016-05-01',name: 'Tom' + i,address: 'No. 189, Grove St, Los Angeles',}tableData.push(obj);}})</script> <style >
.myClass {background-color: rgb(16, 95, 95) !important;color: blueviolet;
}
</style>