vue-pdf 不会在 src 更改时刷新



我正在使用最新的vue-pdf包在我的应用程序中显示pdf文件。我构建了这个组件,PdfViewer:

<template>
<div class="fill-height pdf-container">
<template v-if="src && numberOfPages">
<pdf
v-for="page in numberOfPages"
:key="`${fileName}-${page}`"
:src="src"
:page="page"
/>
</template>
</div>
</template>
import { mapGetters } from 'vuex'
import pdf from 'vue-pdf'
export default {
props: {
fileName: {
type: String,
required: true
}
},
components: {
pdf
},
data() {
return {
src: null,
numberOfPages: 0
}
},
computed: {
...mapGetters({
getAttachments: 'questions/getAttachments'
})
},
methods: {
init() {
if (this.fileName) {
let url = this.getAttachments[this.fileName]
let loadingTask = pdf.createLoadingTask(url)
this.src = loadingTask
this.src.promise.then(pdf => {
this.numberOfPages = pdf.numPages
})
}
},
},
watch: {
fileName() {
this.init()
}
},
beforeMount() {
this.init()
}
}

基本上,我接收一个fileName作为道具,然后在getAttachmentsgetter中接收的对象中查找它的URL。文件名在不同的列表组件中。

它在第一次运行时运行良好,并且成功加载并显示了第一个文件。但一旦点击了另一个文件名,就什么也没显示。我确实收到了文件名道具,它确实找到了URL,但文件没有显示。即使当我点击已经显示的文件时,现在它也没有了。

我想这可能与srcnumberOfPages属性有关,所以我试图在加载文件之前重置它们:

init() {
if (this.fileName) {
this.src = null
this.numberOfPages = 0
let url = this.getAttachments[this.fileName]
let loadingTask = pdf.createLoadingTask(url)
this.src = loadingTask
this.src.promise.then(pdf => {
this.numberOfPages = pdf.numPages
})
}
}

唉,同样的结果。在控制台中,我看到来自pdf.worker.js的以下警告:Warning: TT: invalid function id: 9

不知道这意味着什么。

有什么需要帮忙的吗?

编辑

我试着用async/await和forceUpdate:来做到这一点

async init() {
if (this.fileName) {
this.src = null
this.numberOfPages = 0
let url = this.getAttachments[this.fileName]
let loadingTask = await pdf.createLoadingTask(url)
await loadingTask.promise.then(pdf => {
this.src = url
this.numberOfPages = pdf.numPages
})
this.$forceUpdate()
}
}

这也于事无补。但我发现,一旦我更改了传递的fileName,代码就会转到init()方法,但由于某种原因,它跳过了loadingTask.promise.then部分,没有进入。我必须知道为什么。

很明显,vue-pdf库存在一些问题。最终,我通过在分配fileName道具并重新渲染组件时设置超时来解决这个问题:

<PdfViewer v-if="selectedFileName" :fileName="selectedFileName" />
onFileNameSelected(fileName) {
this.selectedFileName = null
setTimeout(() => {
this.selectedFileName = fileName
}, 0)
}

然后在PdfViewer组件中,它只是:

created() {
this.src = pdf.createLoadingTask(this.getAttachments[this.fileName])
},
mounted() {
this.src.promise.then(pdf => {
this.numberOfPages = pdf.numPages
})
}

这对我来说很管用,不过感觉有点生气。

如果有人在这个问题上绊倒了。这就是问题所在,密钥需要更改,只需比pdf系统自行刷新即可。其描述如下:https://github.com/arkokoley/pdfvuer/issues/28

我只用以下几行就解决了这个问题:

this.pdf_options.numPages = this.pdf_options.numPages +1;
if(isNaN(this.pdf_options.numPages)) {
this.pdf_options.numPages = 0;
}

其中this.pdf_options.numPages=

<pdf
:src="pdfdata"
v-for="i in numPages"
:key="i"
:page="i"
@loading="loaded"
/>

pdf组件中的页面

最新更新