<template>
<div class="pdf-preview">
<pdf ref="pdf" :src="src" :page="pageNum" @page-loaded="pageLoaded($event)" @num-pages="pageTotalNum = $event" @error="pdfError($event)" @progress="onProgress">
</pdf>
<div class="tools" v-if="show">
<div class="fenye">
<div @click="prePage" class="mr10"> 上一页</div>
<div @click="nextPage" class="mr10"> 下一页</div>
<span class="page">{{ pageNum }}/{{ pageTotalNum }}</span>
</div>
</div>
</div>
</template>
<script>
import pdf from "vue-pdf";
export default {
name: "pdfPreview",
props: {
url: {
default: "",
type: String,
},
},
components: {
pdf,
},
data() {
return {
src: "/static/xxx.pdf", // 预览地址
pageNum: 1, // 当前页码
pageTotalNum: 1, // 总页数
Num: 0,
NumA: 0, //总个数
Numnow: 1, //当前个数
show: false,
};
},
created() {
console.log("this:", this);
this.$toast.loading().hide();
},
mounted() {
this.$toast.loading("加载中...");
// 有时PDF文件地址会出现跨域的情况,这里最好处理一下
this.src = pdf.createLoadingTask(this.src);
},
methods: {
// 上一页函数,
prePage() {
if (this.pageNum < this.pageTotalNum) {
return;
}
this.$toast.loading("加载中...");
var page = this.pageNum;
page = page > 1 ? page - 1 : this.pageTotalNum;
this.pageNum = page;
},
// 下一页函数
nextPage() {
if (this.pageNum >= this.pageTotalNum) {
return;
}
this.$toast.loading("加载中...");
var page = this.pageNum;
page = page < this.pageTotalNum ? page + 1 : 1;
this.pageNum = page;
},
// 页面加载回调函数,其中e为当前页数
pageLoaded(e) {
console.log({ e });
this.curPageNum = e;
setTimeout(() => {
this.$toast.loading().hide();
}, 1000);
},
onProgress(status) {
if (status == 1) {
this.show = true;
this.$toast.loading().hide();
}
},
// 抛出错误的回调函数。
pdfError(error) {
console.error(error);
},
},
beforeDestroy() {
this.$toast.loading().hide();
},
};
</script>
<style lang="scss" scoped>
.pdf-preview {
padding: 12px;
.head {
margin-bottom: 10px;
display: flex;
justify-content: space-between;
}
.tools {
position: fixed;
left: 20px;
bottom: 70px;
.fenye {
margin-top: 20px;
font-size: 12px;
display: flex;
// justify-content: space-between;
align-items: center;
.mr10 {
background-color: #eee;
padding: 3px 15px;
border-radius: 4px;
margin-right: 20px;
}
}
}
.page {
margin-left: 10px;
}
}
</style>
vue-pdf使用
最新推荐文章于 2024-10-18 12:27:51 发布