vue-office使用指南

Vue-Office 使用指南

简介

Vue-Office 是一个专门为 Vue.js 设计的 Office 文档预览库,支持 Word、Excel、PowerPoint 和 PDF 文档的在线预览。它提供了简单易用的组件,无需后端转换即可在前端直接预览 Office 文档。

安装

bash 复制代码
npm install @vue-office/docx @vue-office/excel @vue-office/pdf @vue-office/pptx

基础使用

1. Word 文档预览

vue 复制代码
<template>
  <vue-office-docx
    :src="docxUrl"
    @rendered="renderedHandler"
    @error="errorHandler"
  />
</template>

<script setup>
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'

const docxUrl = ref('path/to/document.docx')

const renderedHandler = () => {
  console.log('Word 文档渲染完成')
}

const errorHandler = (err) => {
  console.error('文档渲染错误:', err)
}
</script>

2. Excel 文档预览

vue 复制代码
<template>
  <vue-office-excel
    :src="excelUrl"
    @rendered="renderedHandler"
    @error="errorHandler"
  />
</template>

<script setup>
import VueOfficeExcel from '@vue-office/excel'
import '@vue-office/excel/lib/index.css'

const excelUrl = ref('path/to/spreadsheet.xlsx')
</script>

3. PDF 文档预览

vue 复制代码
<template>
  <vue-office-pdf
    :src="pdfUrl"
    @rendered="renderedHandler"
    @error="errorHandler"
  />
</template>

<script setup>
import VueOfficePdf from '@vue-office/pdf'

const pdfUrl = ref('path/to/document.pdf')
</script>

4. PowerPoint 文档预览

vue 复制代码
<template>
  <vue-office-pptx
    :src="pptxUrl"
    @rendered="renderedHandler"
    @error="errorHandler"
  />
</template>

<script setup>
import VueOfficePptx from '@vue-office/pptx'

const pptxUrl = ref('path/to/presentation.pptx')
</script>

完整示例:Office 文档预览组件

以下是一个完整的 Office 文档预览组件实现,支持文件上传和多种格式预览:

vue 复制代码
<template>
  <div class="office-preview">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>Office 文档预览</span>
          <el-button @click="goBack" size="small">返回</el-button>
        </div>
      </template>

      <div class="upload-section">
        <el-upload
          :auto-upload="false"
          :on-change="handleFileChange"
          :show-file-list="false"
          accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"
        >
          <el-button type="primary">选择文件</el-button>
        </el-upload>
        <span v-if="currentFile" class="file-name">{{ currentFile.name }}</span>
      </div>

      <div class="preview-container" v-if="fileUrl">
        <!-- Word 文档预览 -->
        <vue-office-docx
          v-if="fileType === 'docx'"
          :src="fileUrl"
          @rendered="renderedHandler"
          @error="errorHandler"
        />

        <!-- Excel 文档预览 -->
        <vue-office-excel
          v-else-if="fileType === 'excel'"
          :src="fileUrl"
          @rendered="renderedHandler"
          @error="errorHandler"
        />

        <!-- PDF 文档预览 -->
        <vue-office-pdf
          v-else-if="fileType === 'pdf'"
          :src="fileUrl"
          @rendered="renderedHandler"
          @error="errorHandler"
        />

        <!-- PPT 文档预览 -->
        <vue-office-pptx
          v-else-if="fileType === 'pptx'"
          :src="fileUrl"
          @rendered="renderedHandler"
          @error="errorHandler"
        />

        <div v-else class="no-preview">
          <el-empty description="不支持的文件类型" />
        </div>
      </div>

      <div v-else class="empty-state">
        <el-empty description="请选择要预览的文件" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import VueOfficePdf from '@vue-office/pdf'
import VueOfficePptx from '@vue-office/pptx'
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'

const router = useRouter()
const currentFile = ref(null)
const fileUrl = ref('')
const fileType = ref('')

// 处理文件选择
const handleFileChange = (file) => {
  currentFile.value = file.raw

  // 根据文件扩展名判断文件类型
  const fileName = file.name.toLowerCase()
  const extension = fileName.substring(fileName.lastIndexOf('.') + 1)

  if (['doc', 'docx'].includes(extension)) {
    fileType.value = 'docx'
  } else if (['xls', 'xlsx'].includes(extension)) {
    fileType.value = 'excel'
  } else if (extension === 'pdf') {
    fileType.value = 'pdf'
  } else if (['ppt', 'pptx'].includes(extension)) {
    fileType.value = 'pptx'
  } else {
    fileType.value = 'unknown'
  }

  // 创建 Blob URL
  fileUrl.value = URL.createObjectURL(file.raw)
}

// 文档渲染完成回调
const renderedHandler = () => {
  console.log('文档渲染完成')
}

// 文档渲染错误回调
const errorHandler = (err) => {
  console.error('文档渲染错误:', err)
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 清理 Blob URL
const cleanup = () => {
  if (fileUrl.value) {
    URL.revokeObjectURL(fileUrl.value)
    fileUrl.value = ''
  }
}
</script>

<style scoped>
.office-preview {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-name {
  color: #606266;
  font-size: 14px;
}

.preview-container {
  min-height: 600px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  overflow: auto;
}

.empty-state {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-preview {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

核心功能说明

1. 文件类型识别

根据文件扩展名自动识别文档类型:

javascript 复制代码
const handleFileChange = (file) => {
  const fileName = file.name.toLowerCase()
  const extension = fileName.substring(fileName.lastIndexOf('.') + 1)

  if (['doc', 'docx'].includes(extension)) {
    fileType.value = 'docx'
  } else if (['xls', 'xlsx'].includes(extension)) {
    fileType.value = 'excel'
  } else if (extension === 'pdf') {
    fileType.value = 'pdf'
  } else if (['ppt', 'pptx'].includes(extension)) {
    fileType.value = 'pptx'
  }
}

2. Blob URL 创建

使用 URL.createObjectURL() 创建本地文件预览链接:

javascript 复制代码
fileUrl.value = URL.createObjectURL(file.raw)

3. 内存管理

使用完毕后释放 Blob URL,避免内存泄漏:

javascript 复制代码
const cleanup = () => {
  if (fileUrl.value) {
    URL.revokeObjectURL(fileUrl.value)
    fileUrl.value = ''
  }
}

4. 事件处理

  • @rendered: 文档渲染完成时触发
  • @error: 文档渲染出错时触发

支持的文件格式

格式 扩展名 组件
Word .doc, .docx @vue-office/docx
Excel .xls, .xlsx @vue-office/excel
PowerPoint .ppt, .pptx @vue-office/pptx
PDF .pdf @vue-office/pdf

注意事项

  1. CSS 样式引入: Word 和 Excel 组件需要引入对应的 CSS 文件
  2. 内存管理: 使用 Blob URL 时记得及时释放,避免内存泄漏
  3. 文件大小: 大文件预览可能会影响性能,建议对文件大小进行限制
  4. 浏览器兼容性: 确保目标浏览器支持相关特性

进阶用法

自定义配置

Excel 组件支持更多配置选项:

vue 复制代码
<vue-office-excel
  :src="excelUrl"
  :options="excelOptions"
  @rendered="renderedHandler"
/>

<script setup>
const excelOptions = {
  minColLength: 10,
  minRowLength: 20,
  widthRatio: 0.1,
  heightRatio: 0.1
}
</script>

从 URL 加载

除了本地文件,也可以从 URL 加载文档:

javascript 复制代码
const fileUrl = ref('https://example.com/document.docx')

总结

Vue-Office 提供了简单高效的 Office 文档预览解决方案,通过组件化的方式让文档预览变得非常简单。结合 Element Plus 的 Upload 组件,可以快速实现文件上传和预览功能。

相关推荐
wuhen_n2 小时前
LeetCode -- 349. 两个数组的交集(简单)
前端·javascript·算法·leetcode
weixin_462446232 小时前
Node.js 纯 JS 生成 SVG 练字纸(米字格 / 田字格)完整实现解析
开发语言·javascript·node.js
cypking2 小时前
三、NestJS 开发实战文档-->集成 MySQL(TypeORM)
前端·数据库·mysql·adb·node.js
dreams_dream2 小时前
Element UI菜单折叠后的el-menu-item属性无法修改问题解决
前端·vue
duanyuehuan2 小时前
vueRouter重置路由
前端·javascript·vue.js
Misnearch2 小时前
npm包-serve包使用
前端·npm·node.js
IT_陈寒2 小时前
React 18 性能优化实战:5个被低估的Hooks用法让你的应用快30%
前端·人工智能·后端
阿珊和她的猫2 小时前
页面停留时长埋点实现技术详解
开发语言·前端·javascript·ecmascript
chilavert3182 小时前
技术演进中的开发沉思-275 AJax : Slider
前端·javascript·ajax·交互