vue3 节流指令-运用滚动事件

291 阅读1分钟

节流: 间隔n秒内重复执行方法,只执行最后一次的方法

可以在man.ts 文件中编写指令,或者抽离出指令

const { createApp } = Vue
// 节流指令
function throttleScroll(event: Event, dealy: number, oldTime: number, setTime: Function) {
  const target: any = event.target || {}
  const clientHeight = target?.clientHeight
  const scrollTop = Math.ceil(target?.scrollTop)
  const scrollHeight = target?.scrollHeight
  // 滑到底部
  const isBottom = clientHeight + scrollTop >= scrollHeight
  // 滑到顶部
  const isTop = scrollTop === 0
  const newTime = Date.now()
  let diff = dealy - (newTime - oldTime)
  diff = diff >= 0 ? diff : 0
  // 临界点判断
  if (!diff || isBottom || isTop) {
    setTime(newTime)
  } else {
    // 阻止事件冒泡并且阻止该元素上同事件类型的监听器被触发
    event?.stopImmediatePropagation()
  }
}
const app = createApp()
app.directive('throttle', {
  created(el, binding) {
    // el绑定指令的元素 binding 里面对象,里面包含了传递的参数等信息
    const dealy = binding.value ?? 200
    let oldTime = Date.now()
    function setTime(data: number) {
      oldTime = data
    }
    el.addEventListener('scroll', (event: Event) => throttleScroll(event || {}, dealy, oldTime, setTime))
  },
  beforeUnmount(el) {
    el.removeEventListener('scroll', throttleScroll)
  },
})

使用

<div v-throttle="1000" @scroll="scroll">