1、在项目中引入插件docx-preview
npm i docx-preview
此插件依赖jszip,所以还要下载jszip:npm i jszip
2、点击在线预览按钮请求接口获取文件流
const blob = new Blob([resp.data])
const url = URL.createObjectURL(blob);//浏览器本地存储不能直接存储blob对象,所以转成字符串
sessionStorage.setItem('myBlob', url);
window.open('/preview', '_blank');//跳转预览页面
3、preview.vue
<template>
<div class="my-component" ref="preview">
</div>
</template>
<script>
const docx = require("docx-preview");
window.JSZip = require("jszip");
// import {base64ToBlob} from '@/utils/util'
export default {
mounted(){
this.getFile()
},
methods: {
getFile() {
this.pageLoading = this.$loading()
// 从 sessionStorage 中获取字符串并转换为 Blob
const storedUrl = sessionStorage.getItem('myBlob');
const retrievedBlob = fetch(storedUrl).then(response => response.blob());
if (retrievedBlob) {
this.$nextTick(()=>{
docx.renderAsync(retrievedBlob, this.$refs.preview);
})
}
this.pageLoading.close()
},
}
}
</script>