vue3+ts预览和下载word,pdf,excel


前言

最近项目一直在做一些文档方面的相关操作,例如查看文件,做文件导出,一般的导出格式为word,excel,pdf 等,我这边是用的第三方插件来实现的此功能,在保证项目的兼容性基础上进行使用,用到的插件是 vue-office


一、vue-office相比其他库的优势?

  1. 使用简单,对新手友好,即传递一个文件地址,就可实现预览。
  2. 提供多种文件的一站式预览解决方案,解决常见的docx、excel、pdf三种文件的预览。
  3. 预览效果也好,不只是对内容预览,也要支持样式。

二、使用步骤

1.引入库

代码如下(示例):

#docx文档预览组件
npm install @vue-office/docx

#excel文档预览组件
npm install @vue-office/excel

#pdf文档预览组件
npm install @vue-office/pdf

特别说明:此插件支持vue2/vue3 且打包没有任何兼容性错误。

2.组件封装

代码如下以docx为(示例):

<template>
  <vue-office-docx :src="excel" class="docx-calss" />
</template>

<script setup lang='ts'>
import {
    
     ref } from 'vue'
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
//引入相关样式
import '@vue-office/docx/lib/index.css'
const props = defineProps({
    
    
  excel: {
    
    
    type: ArrayBuffer,
    default: null
  }
})
</script>
<style scoped lang='scss'>
.docx-calss {
    
    
  height: calc(100vh - 60px);
}
</style>

3.组件使用

父组件直接引入使用(这里是以预览为例)

<template>
  <FullScreenDialog :title="dialog.title" :width="dialog.width" :screenFlag="dialog.screenFlag" :visible="dialog.visible"
    v-if="dialog.visible" :showFooter="dialog.showFooter" @onClose="onClose" @onConfirm="confirm">
    <template v-slot:content>
    <!-- 12222 -->
    <!-- 需要什么东西 1 三个组件 2 不知道 3 如何异步加载组件 4 其他优化暂时不知道 -->
    <caseExcel :excel="excel" v-if="fileType==='xlsx'"></caseExcel>
    <caseDocx :excel="excel" v-if="fileType==='docx'"></caseDocx>
    <casePdf :excel="excel" v-if="fileType==='pdf'"></casePdf>
    </template>
  </FullScreenDialog>
</template>

<script setup lang='ts'>
import {
    
     reactive, ref } from 'vue'
import {
    
    testCaseDownload} from '@/api/test/test'
import caseDocx from '@/components/caseDocx.vue';
import caseExcel from '@/components/caseExcel.vue';
import casePdf from '@/components/casePdf.vue';
import useDialog from '@/hooks/useDialog';
import {
    
    getFileType} from '@/utils/index'
const {
    
     dialog, onShow } = useDialog()
const onClose = () => {
    
    
  dialog.visible = false
}
const excel=ref()
const fileType = ref()
console.log('直接使用的组件');
console.log('直接使用的组件');
console.log('直接使用的组件');
console.log('直接使用的组件');
console.log('直接使用的组件');

const confirm = () => {
    
     }
const  show=async(type,row)=>{
    
    
  dialog.title=row.fileName
  dialog.showFooter=false
  dialog.screenFlag=true
  onShow()
  const  url = `/testCase/download?fileName=${
    
    row.fileName}&path=${
    
    row.path}`
  fileType.value = getFileType(row.fileName)
  const res = await testCaseDownload(url)
  excel.value=res
}
defineExpose({
    
    
  show
})

如果是下载的话只需要传入指定的值,如下图所示:
在这里插入图片描述

总结

以上便是今天发表的所有内容,欢迎有需要的童鞋借鉴使用,如有相关问题,请私聊或评论,如有不足,欢迎批评指正。

猜你喜欢

转载自blog.csdn.net/weixin_48211022/article/details/131126032