Bootstrap

vue-pdf实现pdf文件预览和分页

我采用的是dialog封装的弹窗组件

npm install --save vue-pdf

组件

<template>
  <div>
    <el-dialog
      title=""
      :visible.sync="dialogShow"
      width="655px"
      :append-to-body="true"
      :before-close="handleClose"
      top="0px"
    >
      <VuePdf 
        v-if="fileUrl" 
        class="file_view" 
        :src="fileUrl" 
        :page="currentPage" 
        @num-pages="pageCount=$event" 
        @page-loaded="currentPage=$event"  
        @loaded="loadPdf"
      />
      <div class="pageButton">
          <el-button size="mini" @click="changePage(0)" round>上一页</el-button>
          <el-button size="mini" @click="changePage(1)" round>下一页</el-button>
      </div>
    </el-dialog>
  </div>
</template>
import VuePdf from "vue-pdf";
export default {
  name: "PdfView",
  components: {
    VuePdf,
  },
  props: {
  	//pdf地址
    fileUrl: {
      type: String,
      default: "",
    },
    //控制弹窗显示
    show: {
      type: Boolean,
      require: false
    },
  },
  watch: {
  	//监听到弹窗显示时,页数初始化到第一页
    show: {
      handler(newVal) {
        this.dialogShow = newVal
        this.currentPage = 1
      },
      immediate: true,
    },
  },
  data() {
    return {
      dialogShow:false,
      currentPage: 0, // 页码
      pageCount: 0, // 总页数
    };
  },
  methods: {
    changePage (val) { 
        if (val === 0 && this.currentPage > 1) { 
          this.currentPage --;
        }
        if (val === 1 && this.currentPage < this.pageCount) { 
          this.currentPage ++;
        }
    },
    // 加载的时候先加载第一页
    loadPdf () { 
        this.currentPage = 1 
    },
    //子传父 事件发射,关闭弹窗
    handleClose(){
      this.$emit('closeShow')
    }
  }
};
.pageButton{
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

父组件组件引入

<PdfView
  :fileUrl="pdfUrl"
  :show="pdfShow"
  @closeShow="closeShow"
></PdfView>
import PdfView from "./PdfView.vue";

components: { PdfView },

data() {
    return {
		pdfUrl: "", //点击的pdf地址
		pdfShow: false,//控制组件显示
    }
 }

mounted() {
	 this.pdfUrl = 'XXXXXX.pdf';
     this.pdfShow = true;
},

//接收子组件的关闭
closeShow() {
  this.pdfShow = false;
},
;