element-plus 表格-定位到指定行

表格数据量一页占不下的时候,需要定位到指定的行,显示在可视区域中。采用

scrollTo滚动到一组特定坐标(options: ScrollToOptions | number, yCoord?: number)

核心代码

/*
 * 滚动到指定行 tableScrollToRow
 tableElement:表格元素  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].offsetHeight
    if (!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);
}

/*
 * 滚动到指定行 tableScrollToRow
 tableElement:表格元素  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].offsetHeight
    if (!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>

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值