写在前面:
整理下 本地跑项目可能出现跨域问题无法看到效果 简单就直接提交到线上去 到线上就好了
1.简单使用vue-pdf 无翻页
引用: npm install --save vue-pdf
<template>
<div>
<pdf :src="benyeshuju.linkUrl"></pdf>
<a :href="benyeshuju.linkUrl">
<van-button class="btn" type="primary">
下载资料
</van-button>
</a>
</div>
</template>
<script>
import axios from "axios";
import pdf from 'vue-pdf'
export default {
components: { pdf },
data() {
return {
id: "",
benyeshuju: "",
};
},
created() { //created 里面就是从服务器获取pdf的地址 根据自己的需求去改
axios
.post("/api/resource/detail ", {
id: this.id,
})
.then((res) => {
this.benyeshuju = res.data.data;
});
},
methods: {},
};
</script>
2 复杂使用
<template>
<div>
<pdf
:src="src"
:page="currentPage"
@num-pages="pageCount = $event"
@page-loaded="currentPage = $event"
@loaded="loadPdfHandler"
>
</pdf>
<p class="arrow">
<!-- // 上一页 -->
<span @click="changePdfPage(0)" class="turn" :class="{ grey: currentPage == 1 }"
>上一页</span
>
{{ currentPage }} / {{ pageCount }}
<!-- // 下一页 -->
<span
@click="changePdfPage(1)"
class="turn"
:class="{ grey: currentPage == pageCount }"
>下一页</span
>
</p>
<a :href="benyeshuju.linkUrl">
<van-button class="btn" @click="btn_duihuan" type="primary">下载资料</van-button>
</a>
</div>
</template>
<script>
import axios from "axios";
import pdf from "vue-pdf";
export default {
components: { pdf },
data() {
return {
id: "",
benyeshuju: "",
currentPage: 0, // pdf文件页码
pageCount: 0, // pdf文件总页数
fileType: "pdf", // 文件类型
src: "", // pdf文件地址 不用动下面赋值
};
},
created() { //created 里面就是从服务器获取pdf的地址 根据自己的需求去改
this.id = this.$route.query.id;
axios
.post(" /api/resource/detail ", {
id: this.id,
})
.then((res) => {
this.benyeshuju = res.data.data;
this.src = pdf.createLoadingTask(this.benyeshuju.linkUrl);
//防止本地跨域 但是好像没有用
});
},
methods: {
changePdfPage(val) {
// 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; // 加载的时候先加载第一页
},
},
};
</script>