在做项目的时候会遇到docx
、xlsx
、pdf
等文件的在线预览需求,实现此需求可以有多种解决方式,本文基于vue-office
实现纯前端的文件预览。
如下图,分别为docx
、xlsx
、pdf
三种类型的文件在线加载后的效果。你也可以访问官方预览网址查看效果。
在package.json
文件中添加如下依赖,并通过命令npm i
安装依赖。
{
...,
"dependencies": {
"@vue-office/docx": "1.6.0",
"@vue-office/excel": "1.6.0",
"@vue-office/pdf": "1.6.0"
},
}
在vue
文件中引入依赖,示例代码如下:
//引入相关样式
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'
//引入VueOffice组件
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import VueOfficePdf from '@vue-office/pdf'
export default {
components: {
VueOfficeDocx,
VueOfficeExcel,
VueOfficePdf
},
}
<template>
<div class="layout-file">
<div class="layout-file-title">{{docx}}</div>
<vue-office-docx :src="docx" @rendered="rendered"/>
</div>
<div class="layout-file">
<div class="layout-file-title">{{excel}}</div>
<vue-office-excel :src="excel" @rendered="rendered"/>
</div>
<div class="layout-file">
<div class="layout-file-title">{{pdf}}</div>
<vue-office-pdf style="height: 100%;" :src="pdf" @rendered="rendered"/>
</div>
</template>
完整的实现代码如下:
<template>
<div class="layout-file">
<div class="layout-file-title">{{docx}}</div>
<vue-office-docx :src="docx" @rendered="rendered"/>
</div>
<div class="layout-file">
<div class="layout-file-title">{{excel}}</div>
<vue-office-excel :src="excel" @rendered="rendered"/>
</div>
<div class="layout-file">
<div class="layout-file-title">{{pdf}}</div>
<vue-office-pdf style="height: 100%;" :src="pdf" @rendered="rendered"/>
</div>
</template>
<script>
//引入相关样式
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'
//引入VueOffice组件
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import VueOfficePdf from '@vue-office/pdf'
export default {
components: {
VueOfficeDocx,
VueOfficeExcel,
VueOfficePdf
},
data() {
return {
pdf: 'http://localhost:18081/doc.pdf',
excel: 'http://localhost:18081/doc.xlsx',
docx: 'http://localhost:18081/doc.docx',
ppt: 'http://localhost:18081/doc.pptx'
}
},
methods: {
rendered() {
console.log('rendered')
}
}
}
</script>
<style lang="scss" scoped>
.layout-file {
width: calc(50% - 1rem);
height: 50%;
float: left;
margin-top: 0.8rem;
margin-right: 0.8rem;
position: relative;
border: 1px solid #f00;
border-radius: 0.3rem;
&:nth-child(1), &:nth-child(2) {
margin-top: 0;
}
.layout-file-title {
position: absolute;
top: 0.5rem;
right: 1.5rem;
background-color: rgba(255,0,0,0.8);
padding: 0.1rem 0.4rem;
z-index: 99;
color: #fff;
border-radius: 0.3rem;
font-size: 12px;
}
}
</style>