vue-自定义指令-监听滚动条

// scroll-load-more.js
export default function(el, binding) {
  const SELECT_DOM = el.querySelector(binding.value.name)
  SELECT_DOM.addEventListener('scroll', function() {
    const scrollHeight = this.scrollHeight
    const scrollTop = this.scrollTop
    const clientHeight = this.clientHeight
    // console.log('scrollHeight:', scrollHeight) // 获取元素内容高度(只读)
    // console.log('scrollTop:', scrollTop)
    // 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
    // console.log('clientHeight:', clientHeight) // 读取元素的可见高度(只读)
    // console.log('是否到达底部:', scrollHeight - scrollTop <= clientHeight)
    if (scrollHeight - scrollTop <= clientHeight) {
      binding.value.handle()
    }
  })
}


注册指令

// main.js
import scrollLoadMore from 'scroll-load-more'
Vue.directive('scroll-load-more', scrollLoadMore)

使用指令

<template>
    <div v-scroll-load-more='{ handle: scrollFunc, name: '.data-list ul'}' class='data-list'>
        <ul>
            <li v-for='item in data'></li>
        </ul>
    <div>
</template>

<script>
    methods: {
        scrollFunc(){
            console.log('滚动到底了')
        }
    }
</script>
posted @ 2021-10-12 12:31  做个笔记  阅读(511)  评论(0编辑  收藏  举报