需要的插件
npm i docx-preview@0.1.4
npm i jszip
预览本地文件
<template>
<div class="my-component" ref="preview">
<input type="file" @change="preview" ref="file">
</div>
</template>
<script>
const docx = require('docx-preview');
window.JSZip = require('jszip')
export default {
methods:{
preview(e){
docx.renderAsync(this.$refs.file.files[0],this.$refs.preview) // 渲染到页面预览
}
}
};
</script>
<style lang="less" scoped>
.my-component{
width: 100%;
height: calc(100vh - 100px);
border: 1px solid #000;
}
</style>
从后台获取文件展示
<template>
<div class="my-component" ref="preview">
</div>
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="viewSourceDocument(scope.row)"
>查看源文档</el-button
>
</template>
<script>
const docx = require("docx-preview");
window.JSZip = require("jszip");
import axios from "axios";
export default {
methods: {
viewSourceDocument(row) {
this.getFile(row.dataPath);
},
getFile(resource) {
var preview = this.$refs.preview
var url = baseURL + "xxx" + encodeURI(resource);
axios({
method: "get",
url: url,
responseType: "blob",
}).then(async res => {
const isLogin = await blobValidate(res.data); // 验证是否为blob格式 这步无所谓,可以直接把res.data传入docx.renderAsync(res.data, this.$refs.preview)
if (isLogin) {
const blob = new Blob([res.data])
docx.renderAsync(blob, this.$refs.preview);
}
})
},
}
}
</script>
<style lang="less" scoped>
.my-component{
width: 100%;
height: calc(100vh - 100px);
border: 1px solid #000;
}
</style>
代码保熟