准备
npm install --save vue-pdf
代码
<template>
<div>
<div v-if="filetype === 'image'">
<img :src="urlLink" alt="" />
</div>
<div v-else-if="filetype === 'office'">
<!-- 分页 -->
<div>
<button @click="changePage(0)"></button>
<span>{{ currentPage }}/{{ pageCount }}</span>
<button @click="changePage(1)"></button>
</div>
<!--pdf -->
<div>
<pdf
:src="urlLink"
:page="currentPage"
@num-pages="pageCount = $event"
@page-loaded="currentPage = $event"
@loaded="loadPdfHandler"
/>
</div>
</div>
<!-- excel -->
<div v-else-if="filetype === 'excel'">
<div v-html="exldata"></div>
</div>
</div>
</template>
<script>
import pdf from "vue-pdf";
export default {
components: {
pdf,
},
data() {
return {
filetype: "",
exldata: [],
// 文件服务地址
fsServerPath: "http://loacalhost:8080",
currentPage: 1,
pageCount: 1,
txtPre: "",
urlLink: "",
fileStudyPage: 1, //已浏览的页码
};
},
methods: {
// record 从父页面传过来obj,包含fileName,fileId
open(record) {
let fileTypeName;
if (record.fileName) {
fileTypeName = record.fileName
.substring(record.fileName.indexOf(".") + 1, record.fileName.length)
.toLowerCase();
}
this.urlLink = "";
if (
fileTypeName === "png" ||
fileTypeName === "jpg" ||
fileTypeName === "jpeg"
) {
this.urlLink = this.fsServerPath + record.fileId;
this.filetype = "image";
} else if (
fileTypeName === "pdf" ||
fileTypeName === "doc" ||
fileTypeName === "docx"
) {
this.currentPage = 1;
this.urlLink = this.fsServerPath + record.fileId;
this.filetype = "office";
this.loadPdfHandler();
} else {
this.filetype = "excel";
this.urlLink = this.fsServerPath + record.fileId;
this.$http.get(this.urlLink).then((res) => {
this.exldata = `<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html">
</head>
<body>
${res}
</body>
</html>`;
});
}
},
changePage(num) {
if (num === 0 && this.currentPage > 1) {
this.currentPage--;
}
if (num === 1 && this.currentPage < this.pageCount) {
this.currentPage++;
}
},
loadPdfHandler() {
this.currentPage = this.fileStudyPage || 1;
},
},
};
</script>