vue实现附件图片png,jpg,jpeg,pdf,doc,docx预览问题,话不多说直接上代码
<!-- template -->
<a @click="yuTap(item)">预览</a><!--item参数是后台返回过来的链接,有png,jpg,jpeg,pdf,doc,docx这些以下格式-->
<el-dialog
:visible="showDoc == true || showPdf == true || showImg == true"
:show-close="true"
:width="'80%'"
class="dialog-div-pre-style"
:before-close="closePreviewClick"
center>
<div v-if="showImg == true" class="dialog-body-content-base-style">
<img :src="images" style="width:100%"/>
</div>
<div v-if="showDoc == true" class="dialog-body-content-base-style">
<iframe frameborder="0"
:src="fileUrl"
width='100%' height="450px">
</iframe>
</div>
<div v-if="showPdf == true" class="dialog-body-content-base-style" style="justify-content: center; align-items: center">
<pdf
ref="pdf"
:src="pdfUrl"
:page="currentPage"
@num-pages="pageCount=$event"
@page-loaded="currentPage=$event"
@loaded="loadPdfHandler"
>
</pdf>
<div style="text-align: center;font-size:20px">
<span @click="changePdfPage(0)" class="turn" :class="{grey: currentPage==1}">上一页</span>
{{currentPage}} / {{pageCount}}
<span @click="changePdfPage(1)" class="turn" :class="{grey: currentPage==pageCount}">下一页</span>
</div>
</div>
</el-dialog>
import pdf from 'vue-pdf';
export default {
data() {
return {
showDoc:false,//判断如果是否为word文件显示
showPdf: false,//判断如果是否为pdf文件显示
showImg:false,//判断如果是否为图片显示
fileUrl: "",//pdf链接
images: "",//图片链接
currentPage: 0, // pdf文件页码
pageCount: 0, // pdf文件总页数
pdfUrl: "",//pdf链接
};
},
methods: {
yuTap(item){
var the = this;
var fie = 'http://'+item //文件路径有域名不需拼接,没有需要拼接一下
var type = item.split('.')[item.split('.').length-1];
if(type == 'jpg'||type == 'png'||type == 'jpeg'){
the.images = fie
the.showImg = true;
}else if(type == 'pdf'){
the.loadPdfHandler();//重置pdf第一页展示
the.pdfUrl = fie;
the.showPdf = true
}else if(type == 'doc'||'docx'){//word预览
the.fileUrl = 'https://view.officeapps.live.com/op/view.aspx?src='+fie;
the.showDoc = true
}
},
closePreviewClick() {
if (this.showDoc == true) {
this.showDoc = false
} else if (this.showPdf == true) {
this.showPdf = false
} else if (this.showImg == true) {
this.showImg = false
}
},
changePdfPage (val) { //pdf上一页下一页操作
// console.log(val)
if (val === 0 && this.currentPage > 1) {
this.currentPage--
// console.log(this.currentPage)
}
if (val === 1 && this.currentPage < this.pageCount) {
this.currentPage++
// console.log(this.currentPage)
}
},
// pdf加载时
loadPdfHandler (e) {
this.currentPage = 1 // 加载的时候先加载第一页
},
}
}
首先框架用的是elementUI做后台管理,因为需求给的是可预览pdf,图片以及word文件,所以自己网上找了一下干货整理了一下,预览展示用的是elementUI的el-dialog弹出框
pdf预览需要安装哦
npm install --save vue-pdf