Vue项目中使用vue-pdf实现PDF文件预览

   最近做项目,遇到预览PDF这个功能,在网上找了找,大多推荐的是pdf.js,不过在Vue中还是想偷懒直接npm组件,最后找到了一个还不错的Vue-pdf 组件,GitHub地址:https://github.com/FranckFreiburger/vue-pdf#readme
不过一般GitHub上的注释比较简洁,所以这里把自己实际使用的过程总结了一下,下面贴代码
 
引用: npm install --save vue-pdf
 
template代码:
<template>
  <div class="pdf" v-show="fileType === 'pdf'">
    <p class="arrow">
    // 上一页
    <span @click="changePdfPage(0)" class="turn" :class="{grey: currentPage==1}">Preview</span>
    {{currentPage}} / {{pageCount}}
    // 下一页
    <span @click="changePdfPage(1)" class="turn" :class="{grey: currentPage==pageCount}">Next</span>
    </p>
    // 自己引入就可以使用,这里我的需求是做了分页功能,如果不需要分页功能,只要src就可以了
    <pdf
      :src="src" // src需要展示的PDF地址
      :page="currentPage" // 当前展示的PDF页码
      @num-pages="pageCount=$event" // PDF文件总页码
      @page-loaded="currentPage=$event" // 一开始加载的页面
      @loaded="loadPdfHandler"> // 加载事件
    </pdf>
  </div>
</template>
js代码:
<script>
  // 引入PDF
  import pdf from 'vue-pdf'
  export default {
    components: {pdf},
    data () {
      return {
        currentPage: 0, // pdf文件页码
        pageCount: 0, // pdf文件总页数
        fileType: 'pdf', // 文件类型
      }
    },
    method: {
      // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
      changePdfPage (val) {
        // console.log(val)
        if (val === 0 && this.currentPage > 1) {
          this.currentPage--
          // console.log(this.currentPage)
        }
        if (val === 1 && this.currentPage < this.pageCount) {
          this.currentPage++
          // console.log(this.currentPage)
        }
      },

      // pdf加载时
      loadPdfHandler (e) {
        this.currentPage = 1 // 加载的时候先加载第一页
      }

    }
  }

</script>

实际效果

猜你喜欢

转载自www.cnblogs.com/steamed-twisted-roll/p/9648255.html