vue滚动触底触发事件容器封装

  • 容器内内容足够多时才会显示滚动条,发生滚动且到达距离底部指定距离后将会触发onReachBottom事件。
  • 容器高度由height控制。
  • 距离底部距离由distance控制。
  • 其他需求请自行修改相关代码。

一、封装组件代码

<template>
  <div class="z-scoll-view-wrapper" :style="{ height: height + 'px' }">
    <div class="z-scoll-view-content" :style="{ height: height + 'px' }" @scroll="scrollEvent">
      <slot name="bodyer"></slot>
      <slot name="footer"></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ZScollView',
  props: {
    // 设置容器高度
    height: {
      type: Number,
      default: 500
    },
    // 设置距离底部多少距离触发onReachBottom事件
    distance: {
      type: Number,
      default: 300
    }
  },
  methods: {
    scrollEvent (e) {
      // 滚动的像素+容器的高度>可滚动的总高度-距离底部高度
      if (e.srcElement.scrollTop + e.srcElement.offsetHeight > e.srcElement.scrollHeight - this.distance) {
        //  触底后触发此事件
        this.$emit('onReachBottom')
      }
    }
  }
}
</script>
<style lang="less">
.z-scoll-view-wrapper {
  width: 100%;
  overflow: hidden;
  .z-scoll-view-content {
    width: 100%;
    overflow-y: auto;
  }
}
</style>

二、使用示例

<template>
  <ZScollView @onReachBottom="onReachBottom" :distance="scollViewConfig.distance" :height="scollViewConfig.height">
    <template #bodyer> 此处存放需要滚动加载的内容 </template>
    <template #footer> 此处可自定义底部动画或者加载完毕提示 </template>
  </ZScollView>
</template>

<script>
import ZScollView from '@/components/ZScollView'
export default {
  name: 'App',
  data () {
    return {
      scollViewConfig: {
        distance: 300, // 距离底部距离300时触发onReachBottom事件
        height: 500 // 容器高度为500
      }
    }
  },
  components: {
    ZScollView
  },
  methods: {
    onReachBottom () {
      // 此处可进行请求后端数据等操作(注意要自行判断是否存在正在请求的接口以进行相关限制)
      console.log('下拉触底了~~~~~~~~~~~~')
    }
  }
}
</script>

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值