Vue项目加载pdf,并且使用滚轮加载分页

400 阅读1分钟

前端q群 398913416 群里面有免费资料纯免费,大家一起学习,如果自己有什么好的学习资料也可以一起分享, 一个人的力量终究有限,共同进步。

安装,个人版本"vue-pdf": "^4.3.0", "vue": "^2.6.11",

npm install --save vue-pdf

初学者可以先去了解一下官网的api和使用方式github地址

代码

<template>
  <div>
    <div class="scrollContainer" ref="scrollContainer" @scroll="handleScroll">
      <div>
        <vue-pdf style="width: 100%;height: 100%;" ref="pdfRef" :src="srcPath" :page="currentPage"
          @num-pages="setTotalPages" @page-loaded="loadNextPage"></vue-pdf>
      </div>
      <!-- 这里展位是表示 pdf 加载的时候向下面有间距,这样就不会看不到pdf最下面的内容 -->
      <div style="height: 40px;visibility: hidden;">111111</div>
    </div>
    {{ currentPage }} / {{ totalPages }}
  </div>
</template>

<script>

export default {
  name: "parstIndex",
  data() {
    return {
      srcPath: "c++.pdf",
      currentPage: 1,
      totalPages: 0,
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // this.$refs.scrollContainer.scroll(0, 0);
    },
    setTotalPages(totalPages) {
      // console.log(totalPages);
      this.totalPages = totalPages;
      this.$nextTick(_ => {
        this.$refs.scrollContainer.scrollTop = 20;
      })
    },
    loadNextPage(loader) {
      console.log(loader);
    },
    handleScroll() {
      const e = this.$refs.scrollContainer;
      console.log(e.offsetHeight, e.scrollHeight, e.scrollTop, e.clientHeight, this.currentPage);
      // 向上滚动 判断是否 == 0 且分页是否大于1
      if (e.scrollTop === 0 && this.currentPage > 1) {
        this.currentPage -= 1;
        return false
      };
      if(this.currentPage > this.totalPages) return
      // console.log(e.offsetHeight, e.scrollHeight, e.scrollTop,e.clientHeight );
      if (e.scrollHeight <= (e.scrollTop + e.offsetHeight + 1)) {
        this.currentPage += 1;
        this.$refs.scrollContainer.scrollTop = 20;
      }
    }
  },
};

</script>

<style lang="scss" scoped>
.scrollContainer {
  width: 500px;
  height: 200px;
  overflow-y: auto;
  padding: 20px 0; // 这里上面隔了20个像素,是为了解决初始化的时候滚动条的值为0,滚动的时候会一直向上滚动进入死循环

  span {
    height: 50% !important; // 可以删除
  }
}
</style>