1. 使用vue-office
父组件调用init方法即,适用于远程url和本地文件
javascript
npm install @vue-office/docx vue-demi
javascript
<template>
<el-dialog
v-el-drag-dialog
:visible.sync="previewOpen"
:close-on-click-modal="false"
append-to-body
custom-class="previewDialog"
@close="closeDialog"
>
<vue-office-docx :src="docx" @rendered="rendered" />
</el-dialog>
</template>
<script>
import VueOfficeDocx from '@vue-office/docx'
import axios from 'axios'
export default {
components: {
VueOfficeDocx
},
data() {
return {
previewOpen: false,
docx: '' // 远程url地址,本次使用blob文件流转url
}
},
beforeDestroy() {
if (this.docx) {
URL.revokeObjectURL(this.docx) // 清除Blob URL
}
},
methods: {
// 预览
init(id) {
axios({
method: 'get',
responseType: 'blob',
url: '' // 自己的服务器,提供的一个word下载文件接口
}).then((res) => {
this.previewOpen = true
this.$nextTick(() => {
this.docx = window.URL.createObjectURL(res.data)
})
})
},
rendered() {
console.log('渲染完成')
},
closeDialog() {
this.previewOpen = false
}
}
}
</script>
<style scoped>
.previewDialog .el-dialog__headerbtn .el-dialog__close {
z-index: 2001;
}
.word {
display: block;
}
</style>
2.使用docx-preview
父组件调用init方法即可,适用于本地文件
javascript
npm install docx-preview
javascript
<template>
<el-dialog
v-el-drag-dialog
:visible.sync="previewOpen"
:close-on-click-modal="false"
append-to-body
custom-class="previewDialog"
@close="closeDialog"
>
<div class="word">
<div ref="myfile" />
</div>
</el-dialog>
</template>
<script>
const docx = require('docx-preview')
import axios from 'axios'
export default {
data() {
return {
previewOpen: false
}
},
methods: {
init(id) {
axios({
method: 'get',
responseType: 'blob',
url: '' // 自己的服务器,提供的一个word下载文件接口
}).then((res) => {
this.previewOpen = true
this.$nextTick(() => {
docx.renderAsync(res.data, this.$refs.myfile)
})
})
},
closeDialog() {
this.previewOpen = false
}
}
}
</script>
<style scoped>
.previewDialog .el-dialog__headerbtn .el-dialog__close {
z-index: 2001;
}
.word {
display: block;
}
</style>