vue2.x + better-scroll2.x 封装列表上滑,下滑行为操作

36 篇文章 0 订阅
5 篇文章 0 订阅

基于vue2.6.11 + better-scroll2.4.2 封装的列表上滑加载,下滑刷新,拿来即用 ~~

better-scroll 是一个移动端滚动的解决方案,它是基于 iscroll 的重写,它和 iscroll 的主要区别在这里better-scroll也很强大,不仅可以做普通的滚动列表,还可以做轮播图、picker 等等。

// 安装插件

npm i better-scroll -S
<template>
  <div ref="scrollRef">
    <div class="scroll-content">
      <slot></slot>

      <!-- loading component -->
      <div>loading - component</div>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'

export default {
  name: 'betterScroll',
  props: {
    /**
     * 1 滚动的时候会派发scroll事件,会截流。
     * 2 滚动的时候实时派发scroll事件,不会截流。
     * 3 除了实时派发scroll事件,在swipe的情况下仍然能实时派发scroll事件
     */
    scrollProbe: {
      type: Number,
      default: 1
    },
    openScroll: {
      type: Boolean,
      default: true
    },
    openPullUp: {
      type: Boolean,
      default: false
    },
    openPullDown: {
      type: Boolean,
      default: false
    },
    /**
     * 滚动列表数据,用于监听异步加载刷新
     */
    scrollDataList: {
      type: Array,
      default: null
    }
  },
  data () {
    return {
      scroll: null
    }
  },
  methods: {
    initScrollEffect () {
      const scrollRef = this.$refs.scrollRef
      if (!scrollRef) {
        console.warn('未初始化DOM实例')
        return false
      }

      const _bsScroll = this.scroll = new BScroll(scrollRef, {
        click: true,
        scrollY: true,
        probeType: this.scrollProbe
      })

      if (this.openScroll) {
        _bsScroll.on('scroll', (pos) => {
          this.$emit('scrollEvents', pos)
        })
      }

      // 是否派发滚动到底部事件,用于上拉加载
      if (this.openPullUp) {
        _bsScroll.on('scrollEnd', () => {
          const { y, maxScrollY } = _bsScroll
          if (y <= (maxScrollY + 50)) {
            this.$emit('pullUpEvents')
          }
        })
      }

      // 是否派发顶部下拉事件,用于下拉刷新
      if (this.openPullDown) {
        _bsScroll.on('touchEnd', (pos) => {
          if (pos.y > 100) {
            this.$emit('pullDownEvents')
          }
        })
      }
    },

    scrollRefresh () {
      this.scroll && this.scroll.refresh()
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.initScrollEffect()
    })
  },
  watch: {
    // 动态加载列表,重新计算高度
    scrollDataList () {
      setTimeout(() => this.scrollRefresh(), 100)
    }
  },
  destroyed () {
    if (this.scroll) {
      this.scroll.destroy()
    }
  }
}
</script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值