最近項目中需求爲在瀏覽器上閱覽PDF格式的文件,之前沒有寫過,隨即上網查閱,發現大家常使用的爲兩個插件。
其一是火狐出品的pdf.js,github地址:https://github.com/mozilla/pd...;
其二是PDFObject,額,不太清楚作者,github地址:https://github.com/pipwerks/P...。
前者功能強大,社區活躍,後者是基於jquery封裝出來的插件,要是在vue中混着jquery總感覺怪怪的,所以我選擇了前者。
又看了一下有沒有輪子可用,誒嘿,vue-pdf,github地址:https://github.com/FranckFrei...。看了文檔,可取。
首先下載插件(建議先新建一個demo出來跑,直接擼到開發項目中...出什麼幺蛾子...)
// 我使用的是yarn npm的話 npm install vue-pdf --dev
yarn add vue-pdf --dev
然後在vue文件中引入使用,建議新建一個vue文件二次封裝
<template>
<div class="pdf-container">
<pdf :src="pdfUrl"/>
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
name: 'VuePdf',
components: { pdf },
data() {
return {
// 此處爲示例pdf地址
pdfUrl: 'http://image.cache.timepack.cn/nodejs.pdf'
}
}
}
</script>
之後就可以愉快的玩耍了。
不過我遷移到公司項目的時候遇到一個坑,引入這個插件的時候就會報錯window is not defined,後來查詢資料發現這篇文章,問題才得已解決,感謝作者。https://blog.csdn.net/u010745...
只需要在webpack中設置如下
module.exports = {
// 請忽視這無關的代碼
output: {
globalObject: "this"
}
// 請忽視這無關的代碼
}
以上。