项目场景:
vue3项目中通过 docx-preview 实现docx格式文件预览
操作步骤:
1.下载 :
npm i docx-preview --save
// 或者
yarn add docx-preview
2.导入
const docx = require('docx-preview');
3.使用
<div>
<el-dialog v-model="wordViewShow" fullscreen title="Tips" width="90%" class="previewWrap">
<div class="top">
<div class="leftName">
<img src="@/assets/img/basicData/word.png" alt="">
{{curFileName}}
</div>
</div>
<div class="bottom" id="bottom" ref="bottom">
<div class="my-component" ref="wordView" id="wordView"></div>
</div>
<div class="delBtn" @click="cancelDialog">
<img style="margin-right:0.5rem" src="@/assets/img/basicData/return.png" alt="">返回
</div>
</el-dialog>
</div>
<script setup>
import axios from 'axios'
//下载 axios npm install axios --save
import { ref, getCurrentInstance, reactive, nextTick } from 'vue'
const { proxy } = getCurrentInstance()
let wordViewShow = ref(false)
let curFileName = ref('')
// 预览
function previewBtn(item, i) {
let url = `${window.location.origin}/api/data/item?category=${window.encodeURIComponent(curItem.value)}&county=${window.encodeURIComponent(item.name)}&item=${i}`
curFileName.value = i
wordViewShow.value = true
console.log(url);
// 确保在网页中输入url可以直接下载docx文件
nextTick(() => {
proxy.$refs.bottom.scrollTop = 0
})
axios({
method: 'get',
responseType: 'blob', // 设置响应文件格式
url,
}).then(({ data }) => {
docx.renderAsync(data, proxy.$refs.wordView) // 渲染到页面预览
})
}
</script>
<style>
.docx-wrapper > section.docx {
margin-bottom: 20px !important;
}
.docx-wrapper {
padding: 0 !important;
background: unset !important;
flex-direction: row !important;
flex-wrap: wrap !important;
justify-content: center !important;
align-items: unset !important;
}
.docx-wrapper section.docx {
width: 66% !important;
overflow-x: auto;
}
.previewWrap .el-dialog__header {
display: none;
}
.previewWrap .el-dialog__body {
padding: 0;
height: 100%;
}
.previewWrap .el-dialog {
height: 50%;
overflow: auto;
}
.previewWrap {
height: 100%;
overflow: auto;
.delBtn {
position: fixed;
right: 31px;
bottom: 20px;
cursor: pointer;
width: 180px;
height: 80px;
background: linear-gradient(180deg, #097ad3 0%, #05599b 100%);
border-radius: 2px;
border: 1px solid #1486e1;
font-size: 24px;
display: flex;
align-items: center;
justify-content: center;
color: #70FFFF;
}
.top {
width: calc(100% - 40px);
height: 60px;
background: linear-gradient(360deg, #02508d 0%, #0864ac 100%);
padding: 0 20px;
display: flex;
justify-content: space-between;
align-items: center;
.leftName {
font-size: 16px;
font-family: Microsoft YaHei-Bold, Microsoft YaHei;
font-weight: bold;
color: #ffffff;
line-height: 60px;
height: 100%;
display: flex;
align-items: center;
img {
margin-right: 10px;
width: 30px;
height: 30px;
}
}
}
.bottom {
width: calc(100% - 40px);
height: calc(100% - 60px);
padding: 0 18px;
overflow: auto;
background: #02508d;
.my-component {
height: calc(100% - 20px);
margin-bottom: 20px;
}
}
}
</style>