在网上找了找,大多推荐的是pdf.js,不过在Vue中还是想偷懒直接npm组件,最后找到了一个还不错的Vue-pdf 组件。结合好几篇文章,最后完美实现自己想要的效果。
引用:npm install --save vue-pdf
页面渲染:
<template>
<div class="pages">
<span @click="changePdfPage(0)" class="turn" :class="{grey: currentPage==1}">
<span style="margin-right:5px"><</span>
</span>
{{currentPage}} / {{pageCount}}
<span @click="changePdfPage(1)" class="turn"
:class="{grey: currentPage==pageCount}">
<span style="margin-left:5px">></span>
</span>
</div>
<pdf ref="pdf"
:page="currentPage"
@num-pages="pageCount=$event"
@page-loaded="currentPage=$event"
@loaded="loadPdfHandler"
:src="pdfUrl"
style="width: 100%;height:96%;overflow:hidden"
class="myScroll"/>
</template>
js逻辑:
<script>
import pdf from 'vue-pdf'
export default {
components:{
pdf
},
data(){
return{
currentPage: 0, // pdf文件页码
pageCount: 0, // pdf文件总页数
pdfUrl: '',
baseURL: process.env.VUE_APP_BASE_API,
url:"",
}
},
methods:{
loadPdfHandler (e) {
this.currentPage = 1 // 加载的时候先加载第一页
},
changePdfPage (val) {
if (val === 0 && this.currentPage > 1) {
this.currentPage--
}
if (val === 1 && this.currentPage < this.pageCount) {
this.currentPage++
}
},
},
created(){
this.file = this.$route.params.file
this.url = this.baseURL + this.$route.params.file.filePath
const path = this.url// 你获取到的pdf路径
this.pdfUrl = pdf.createLoadingTask(path)// pdf.createLoadingTask解决文件件跨域问题
}
}
</script>
实现效果: