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

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

javascript 复制代码
npm install --save vue-pdf

组件

javascript 复制代码
<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>
javascript 复制代码
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')
    }
  }
};
javascript 复制代码
.pageButton{
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

父组件组件引入

javascript 复制代码
<PdfView
  :fileUrl="pdfUrl"
  :show="pdfShow"
  @closeShow="closeShow"
></PdfView>
javascript 复制代码
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;
},
相关推荐
Maimai108086 分钟前
React如何用 @microsoft/fetch-event-source 落地 SSE:比原生 EventSource 更灵活的实时推送方案
前端·javascript·react.js·microsoft·前端框架·reactjs·webassembly
candyTong9 分钟前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
卡卡军3 小时前
agmd 1.0 重磅升级——Rust 重写,性能起飞
javascript·rust
Larcher3 小时前
🔥 告别抓瞎:用 Claude Code (cc) 优雅接手与维护已有项目
javascript·机器学习·前端框架
JYeontu3 小时前
轮播图不够惊艳?试下这个立体卡片轮播图
前端·javascript·css
亲亲小宝宝鸭3 小时前
如何监听DOM尺寸的变化?element-resize-detector 和 resizeObserver
前端·javascript
代码煮茶3 小时前
Vite 5.0 新特性深度解析:更快、更干净、更未来的前端构建利器
vue.js
驯龙高手_追风5 小时前
Adobe Acrobat PDF阅读器设置默认滚动翻页
adobe·pdf·adobe acrobat reader·adobe reader
卷帘依旧6 小时前
Generator 全面解析 + async/await 深度对比
前端·javascript
weixin_471383036 小时前
统一缩放单位基础(px、em、rem)
开发语言·javascript·ecmascript