美文网首页
基于第三方插件better-scroll实现vue滚动分页组件

基于第三方插件better-scroll实现vue滚动分页组件

作者: ZZ_simon | 来源:发表于2018-04-01 14:38 被阅读0次

better-scroll版本:"^1.9.1"

1、实现组件

<!-- better-scroll 滚动分页组件 -->

<template>
  <div ref="wrapper" class="my-scroll">
    <slot></slot>
  </div>
</template>

<script>
import BScroll from "better-scroll";
export default {
  components: {},
  props: {
    // 传入的数据
    totalPage: {
      type: Number,
      default: null
    },
    currentPage: {
      type: Number,
      default: null
    },
    probeType: {
      type: Number,
      default: 1
    },
    click: {
      type: Boolean,
      default: true
    },
    // 是否监听滚动位置
    listenScroll: {
      type: Boolean,
      default: false
    },
    // 是否开启上拉刷新
    pullUpLoad: {
      type: Number,
      default: -50
    },
    // 延迟刷新
    refreshDelay: {
      type: Number,
      default: 20
    }
  },
  methods: {
    _initScroll() {
      if (!this.$refs.wrapper) {
        return;
      }
      this.scroll = new BScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click,
        pullUpLoad: { threshold: this.pullUpLoad }
      });
      // 派发上拉刷新事件
      if (this.pullUpLoad) {
        let me = this;
        me.scroll.on("pullingUp", function(position) {
          if (me.currentPage < me.totalPage) {
            me.$emit("refreshList", me.currentPage + 1);
            me.scroll.finishPullUp();
            me.scroll.refresh();
          }
        });
      }
    },
    refresh() {
      this.scroll && this.scroll.refresh();
    }
  },
  mounted() {
    setTimeout(() => {
      this._initScroll();
    }, 20);
  }
};
</script>

<style lang="less" scoped>
.my-scroll {
  height: 100%;
}
</style>

2、调用组件

<Scroll ref="scroll" @refreshList="_findDoctorArticle" :totalPage="totalPage" :currentPage="currentPage">
  这里一堆dom....
  这里一堆dom....
  这里一堆dom....
</Scroll>

data() {
    return {
      articleList: [],
      currentPage: 1,
      pageSize: 4,
      totalPage: null
    };
  },
  components: {
    Scroll
  },
  methods: {
    //获取热门文章数据
    async _findDoctorArticle(currentPage = 1) {
      this.currentPage = currentPage;
      let currentPageData = await findDoctorArticle(this.pageSize, currentPage);
      this.totalPage = currentPageData.query.totalPage;
      this.articleList = this.articleList.concat(currentPageData.model);
    }
  },
  mounted() {
    this._findDoctorArticle();
  }

相关文章