字节笔记本字节笔记本

Vue3 Element Plus Table 添加滚动事件

2022-07-13

在Vue3和Element Plus的表格组件中添加了滚动事件监听,以实现滚动到表格底部时自动加载更多数据的功能。

const TableRef = ref<ComponentPublicInstance<HTMLInputElement>>()
onMounted(() => {
  getTreeData()
  nextTick(() => {
    if (TableRef.value)
      (TableRef.value.$refs.bodyWrapper as HTMLElement).addEventListener('mousewheel', throttle(scrollBehavior, 1000))
  })
})

onUnmounted(() => {
// 卸载
  TableRef.value && (TableRef.value?.$refs.bodyWrapper as HTMLElement).removeEventListener('mousewheel', scrollBehavior)
})

// 滚动事件
function scrollBehavior(e: any) {
  // console.log(2)
  const scrollDirection = e.deltaY > 0 ? 'down' : 'up'
  if (scrollDirection === 'down') {
    const dom = (TableRef.value?.$refs.bodyWrapper as HTMLElement).getElementsByClassName('el-scrollbar__wrap')[0]
    const { clientHeight, scrollTop, scrollHeight } = dom
    // 父容器高度 + 子容器距离父容器顶端的高度 = 子容器可滚动的高度
    if (clientHeight + scrollTop === scrollHeight)
      getMorePerson()
  }
}