1、安装依赖
npm install --save vue-pdf
2、html部分
<template>
<div class="detail">
<p class="arrow">
<span
@click="changePdfPage(0)"
class="turn previewBtn"
:class="{grey: currentPage==1}"
>上一页</span>
<span class="pageViews"
>{{currentPage}} / {{pageCount }}</span>
<span
@click="changePdfPage(1)"
class="turn nextBtn"
:class="{grey: currentPage==pageCount}"
>下一页</span>
</p>
<div class="pdf-box">
<pdf
:src="pdffile"
:page="currentPage"
@num-pages="pageCount=$event"
@page-loaded="currentPage=$event"
@loaded="loadPdfHandler"
></pdf>
</div>
</div>
</template>
3、script部分
<script>
import pdf from "vue-pdf";
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js';
export default {
data() {
return {
currentPage: 0, // pdf文件页码
pageCount: 0, // pdf文件总页数,
flag: true,
}
},
components: {
pdf,
},
computed: {
path() {
return this.$route.query.path //path是pdf的地址,我是在上个页面路由通过query传过来的,具体根据自己的情况
},
pdffile() {
return pdf.createLoadingTask({
url: this.path,
CMapReaderFactory //这里用来解决部分pdf预览乱码问题,主要是看不到汉字的问题
})
}
},
methods: {
loadPdfHandler (e) {
this.currentPage = 1 // 加载的时候先加载第一页
},
changePdfPage (val) {
if(!this.flag) return
this.flag = false
setTimeout(() => { //这里的定时器用来防止用户频繁点击,我设置的0.5秒内无论点击多少次都只触发一次
this.flag = true
if (val === 0 && this.currentPage > 1) {
this.currentPage--
}
if (val === 1 && this.currentPage < this.pageCount) {
this.currentPage++
}
}, 500)
},
}
}
</script>
4、css部分
<style lang="scss" scoped>
.detail {
width: 100%;
overflow-x: hidden;
.arrow {
display: flex;
text-align: center;
font-size: 20px;
line-height: 50px;
.previewBtn {
flex: 1;
justify-content: center;
align-items: center;
color: #5297f3;
}
.nextBtn {
flex: 1;
justify-content: center;
color: #5297f3;
}
.pageViews {
flex: 2;
text-align: center;
color: #5297f3;
}
.grey {
color: #666;
}
}
}
</style>
vue-pdf 预览乱码问题,请点击这里