vue2 预览 word、excel、pdf
依赖的库
npm install @vue-office/docx
npm install @vue-office/excel
npm install @vue-office/pdf
npm install @vue/composition-api (上面组件需要依赖的库)
代码实现
<template>
<div class="Office-Preview" v-loading="loading" element-loading-text="文件加载中..." >
<VueOfficeDocx v-if="fileType == 'docx'" :src="fileUrl" @rendered="rendered" @error="onError"></VueOfficeDocx>
<VueOfficeExcel v-if="fileType == 'excel'" :src="fileUrl" @rendered="rendered" @error="onError"></VueOfficeExcel>
<VueOfficePdf v-if="fileType == 'pdf'" :src="fileUrl" @rendered="rendered" @error="onError"></VueOfficePdf>
<el-empty v-if="fileType == 'errType'" image="" description="文件格式不规范" :image-size="300"></el-empty>
<el-empty v-if="fileType == 'loadErr'" image="" description="文件加载失败" :image-size="300"></el-empty>
</div>
</template>
<script>
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
//引入VueOfficeExcel组件
import VueOfficeExcel from '@vue-office/excel'
//引入VueOfficeExcel相关样式
import '@vue-office/excel/lib/index.css'
//引入VueOfficePdf组件
import VueOfficePdf from '@vue-office/pdf'
export default {
name: 'Office-Preview',
props: {
fileUrl: {
type: String,
default: '',
},
},
data() {
return {
fileType: '',
loading: true,
}
},
components: {
VueOfficeDocx,
VueOfficeExcel,
VueOfficePdf,
},
methods: {
init() {
if (!this.fileUrl) console.error('文件为空')
var fileName = this.fileUrl.split('/').pop()
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1)
if (fileExtension == 'doc' || fileExtension == 'docx') {
this.fileType = 'docx'
} else if (fileExtension == 'xls' || fileExtension == 'xlsx') {
this.fileType = 'excel'
} else if (fileExtension == 'pdf') {
this.fileType = 'pdf'
} else if (fileExtension == 'ppt' || fileExtension == 'pptx') {
this.fileType = 'ppt'
} else {
this.fileType = 'errType'
this.loading = false
}
},
rendered() {
console.log('渲染完成')
this.loading = false
},
onError() {
console.error('加载戳错')
this.loading = false
this.fileType = 'loadErr'
},
},
created() {
this.init()
},
}
</script>
<style lang="scss" scoped>
.Office-Preview {
overflow-y: scroll;
height: 100%;
}
</style>