使用vue-pdf,并把它封裝成一個文件后,第一次調(diào)用是沒有問題的,問題是當(dāng)你切換pdfUrl的時候,pdf并不會馬上置換掉,再點擊一次的時候才會置換成新的pdfurl
由于父子組件存在調(diào)用,出現(xiàn)了,pdf預(yù)覽每次只能查看一個,別的打開空白:
安裝依賴
npm install --save vue-pdf
將vue-pdf封裝成一個組件
<template>
<div>
????????v-for="i in numPages"
????????:key="i"
????????:src="src"
????????:page="i"
????????></pdf>
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
? ? name: 'vuePdf',
????components: {
????},
? ? props: {
? ? pdfSrc: {
? ? ? ? type: String,
? ? ? ? ? ? require: true
? ? ? ? }
? ? },
data() {
return {
????src: '',
????????numPages: undefined,
????}
},
mounted() {
? this.loadPDF(this.pdfSrc)
},
methods:{
loadPDF(url){
????this.src=pdf.createLoadingTask(url)
????this.src.promise.then(pdf => {
????????this.numPages = pdf.numPages;//獲取pdf頁數(shù)
????});
},
//很重要,父組件關(guān)閉前,清空子組件的值,不然第二次預(yù)覽打開空白
????resetPageNum(){
????????this.numPages=undefined
????}
}
}
</script>
父組件中使用
html部分:先引入注冊,在使用
import vuePdf from './pdf'
components: { vuePdf}
<van-popup v-model="show" round position="bottom" :close-on-click-overlay="false" :style="{ height: '80%' }">
<div>
? ? ? <vue-pdf ref="mypdf" :pdf-src="fileUrl" :key="fileId"></vue-pdf>
? </div>
</van-popup>
//關(guān)閉pdf彈窗的方法
closePopup(){
? ? //調(diào)用子組件的重置數(shù)據(jù)方法,解決空白問題
? ? this.$refs.mypdf.resetPageNum()
? ? this.show=false
},
//預(yù)覽的方法,傳入id通過接口查詢pdf的url
showpdf(id) {? ?
? ? this.fileUrl =?https://aliyuncs.com/applet/fb3e9155150141da94e3b22271dc06.pdf
? ? this.fileId = id
? ? this.show = true
},
解決方案:
通過子組件定義清空數(shù)據(jù)的方法,在父組件關(guān)閉子組件彈窗前調(diào)用,讓子組件重新刷新頁面,重新渲染.