在项目中很多时候需要用到表格或数据的自动滚动,本文抽离出代码成为一个hooks,大家复制即可使用,记得要消化后再食用,效果更佳。
- 首先我们先写个通用的hooks
文件位置:src/hooks/index.ts
/**
滚动条自动滚动
*/
export const useAutoScroll=()=>{
const timer=ref<null | number >(null);
//删除定时器
const clearScroll = () => {
timer.value && clearInterval(timer.value)
timer.value = null
}
//创建定时器,tableWrapper是滚动条的dom,_timeout是多久动一下
const createScroll = (tableWrapper:HTMLElement,_timeout:number=100) => {
clearScroll()
//内容高度小于等于可视高度则不进行滚动
if(tableWrapper!.scrollHeight <= tableWrapper!.clientHeight){
return
}
timer.value = setInterval(() => {
tableWrapper!.scrollTop += 1
// 判断是否滚动到底部,如果到底部了置为0(可视高度+距离顶部=整个高度)
if (tableWrapper!.clientHeight + tableWrapper!.scrollTop == tableWrapper!.scrollHeight) {
tableWrapper!.scrollTop = 0
}
}, _timeout)
}
//关闭组件需要的操作
onBeforeUnmount(() => {
clearScroll()
})
return{
clearScroll,createScroll
}
}
- 然后引入到vue文件中 ,表格的高度是具体的值才会生效
<template>
<el-table
ref="tableRef"
@mouseover="clearScroll"
@mouseleave="setDynamicScroll"
:data="listData"
:height="tableHeight"
</el-table>
</template>
<script setup lang="ts">
import { useAutoScroll } from "@/hooks";
const tableRef = ref()
const tableHeight=ref('100px')//这个表格高度你也可以动态获取,当然这个时候需要考验你的代码整合能力了
const {createScroll,clearScroll }=useAutoScroll()
const setDynamicScroll=()=>{
//这里获取滚动的div元素方法有很多,这里展示其中一种
const table = tableRef.value.layout.table.refs;
// 拿到可以滚动的元素
const tableWrapper = table.bodyWrapper.firstElementChild.firstElementChild;
createScroll(tableWrapper)
}
onMounted(() => {
setDynamicScroll()
});
</script>
--------有用的请在评论区扣上“有用”
--------有疑问或有错误点也欢迎在评论区评论。
--------点赞,关注,评论三连。谢谢!