vue封装better-scroll组件

先下载better-scroll

npm install better-scroll --s

scroll.vue的DOM

<template>
  <div ref="wrapper">
    <slot></slot>
  </div>
</template>

scroll.vue的JS

<script type="text/ecmascript-6">
  import BScroll from 'better-scroll';
  export default {
    props: {
      probeType: { // 派发滚动事件方式
        type: Number,
        default: 1
      },
      click: { // 是否支持点击
        type: Boolean,
        default: true
      },
      data: {
//        type: Array,
        default: null
      },
      scrollX: { // 设置滚动方向为x轴
        type: Boolean,
        default: false
      },
      listenScroll: { // 监听滚动
        type: Boolean,
        default: false
      },
      pullup: { // 开启上拉刷新
        type: Boolean,
        default: false
      },
      beforeScroll: { // 滚动开始派发
        type: Boolean,
        default: false
      },
      refreshDelay: { // 控制刷新时间(内部如果包含动画切换,需要增加延时)
        type: Number,
        default: 20
      },
      eventPassthrough: { // 忽略滚动的方向
        type: String,
        default: ''
      }
    },
    mounted() {
      setTimeout(() => {
        this._initScroll();
      }, 20);
    },
    methods: {
      _initScroll() {
        if (!this.$refs.wrapper) {
          return;
        }
        this.scroll = new BScroll(this.$refs.wrapper, {
          probeType: this.probeType,
          click: this.click,
          scrollX: this.scrollX,
          eventPassthrough: this.eventPassthrough
        });
        // 是否需要监听滚动事件
        if (this.listenScroll) {
          this.scroll.on('scroll', (pos) => {
            this.$emit('scroll', pos);
          });
        }
        // 如果支持上拉刷新
        if (this.pullup) {
          this.scroll.on('scrollEnd', () => {
            if (this.scroll.y <= this.scroll.maxScrollY + 50) { // 快滚动到底部
              this.$emit('scrollToEnd'); // 派发事件说明已经滚动到底部
            }
          });
        }
        // 在触发滚动之前派发事件,这里主要用于用户体验优化
        if (this.beforeScroll) {
          this.scroll.on('beforeScrollStart', () => {
            this.$emit('beforeScroll');
          });
        }
      },
      enable() {
        this.scroll && this.scroll.enable();
      },
      disable() {
        this.scroll && this.scroll.disable();
      },
      refresh() {
        this.scroll && this.scroll.refresh();
      },
      scrollTo() {
        this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments);
      },
      scrollToElement() {
        this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments);
      }

    },
    watch: {
      data() { // 可以手动设置更新延时,视情况而定
        setTimeout(() => { // 重新计算滚动高度
          this.refresh();
        }, this.refreshDelay);
      }
    }
  };
</script>

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值