vue实现滚动底部加载下一页指令的示例代码

  Vue.directive('scroll',{

  bind(el,binding) {

  let p = 0

  let t = 0

  let down = true

  let timer = null

  el.handler = () => {

  p = window.pageYOffset ||

  document.documentElement.scrollTop ||

  document.body.scrollTop

  if (t < p) {

  down = true

  } else {

  down = false

  }

  t = p

  let sign = 10

  let scrollHeight=document.documentElement.scrollHeight//滚动条的高度

  let clientHeight=document.documentElement.clientHeight//浏览器的可视高度

  const scrollDistance = scrollHeight -p -clientHeight

  if (scrollDistance < sign && down) {

  if (timer) clearTimeout(timer)

  timer = setTimeout(() => {

  binding.value()

  }, 300)

  }

  }

  setTimeout(() => {

  window.addEventListener('scroll',el.handler)

  },1000)

  },

  //只有绑定不解绑的话,会出现在页面加载的时候调用之前请求过的接口的情况,所以加上解绑比较好

  unbind(el) {

  window.removeEventListener('scroll',el.handler)

  }

  })