一、在线预览组件代码封装
1、文件目录截图
![在这里插入图片描述](https://img-blog.csdnimg.cn/b1f58dadd54444ffa3765b08541076f6.png)
2、文件代码
(1)preview-file.vue 文件内容
<template>
<!--
1-先安装插件,执行命令:npm i --save video.js
2-在main.js文件中引入:
import 'video.js/dist/video-js.min.css'
import previewFile from '@/components/preview-file'
Vue.use(previewFile)
使用:
<preview-file :file="file" ref="previewFile"></preview-file>
data() {
return {
file: {
visible: false,
title: '',
url: ''
}
}
},
methods: {
onPreview (file) {
if (file.response !== null && file.response !== undefined && file.response !== '') {
this.file.visible = true
this.file.title = file.response.data.fileName
this.file.url = file.response.data.src
this.$refs.previewFile.init()
} else {
this.$message.info('文件正在上传,等上传完成后再预览!')
}
}
}
-->
<el-dialog :visible.sync="this.file.visible" :title="`${this.file.title}`" :before-close="handleClose" :width="this.width" :close-on-click-modal="false" :close-on-press-escape="false" top="0" append-to-body>
<div v-if="this.isImage" style="text-align: center;">
<img :src="this.file.url" width="100%" alt />
</div>
<div v-else-if="this.isPdf">
<iframe :src="this.file.url" width="100%" :height="this.iframeH" frameborder="0"/>
</div>
<div v-else-if="this.isAudio">
<!-- autoplay="autoplay" 支持自动播放音频文件 -->
<template>
<audio :src="this.file.url" controls="controls" ref="audio" style="width: 100%;">
您的浏览器不支持音频元素。
</audio>
<div style="width: 100%;text-align: center;margin-top: 20px;margin-bottom: 20px;">
<el-button width="18rem" size="small" plain @click="playAudio">播放</el-button>
<el-button width="18rem" size="small" plain @click="pauseAudio">暂停</el-button>
<el-button width="18rem" size="small" plain @click="stopAudio">停止</el-button>
</div>
</template>
</div>
<div class="videoArea" v-else-if="this.isVideo">
<video ref="videoPlayer" controls :src="this.file.url" @timeupdate="updateTime" :class="['movie-show-video']" style="width: 100%; height: 100%; object-fit: fill"></video>
<div style="width: 100%;text-align: center;margin-top: 20px;margin-bottom: 20px;">
<el-button width="18rem" size="small" plain @click="playVideo">播放</el-button>
<el-button width="18rem" size="small" plain @click="pauseVideo">暂停</el-button>
<el-button width="18rem" size="small" plain @click="stopVideo">停止</el-button>
<el-button width="18rem" size="small" plain @click="forwardVideo">前进</el-button>
<el-button width="18rem" size="small" plain @click="backVideo">倒退</el-button>
</div>
</div>
<div v-else-if="this.isOffice">
<iframe :src="`https://view.officeapps.live.com/op/view.aspx?src=${this.file.url}`" width="100%" :height="this.iframeH" frameborder="0"/>
</div>
<div v-else style="text-align: center;">
暂不支持在线预览
</div>
</el-dialog>
</template>
<script>
export default {
name: 'PreviewFile',
props: {
file: {
type: Object,
default: function () {
return {
visible: false,
title: '',
url: ''
}
}
}
},
data () {
return {
isImage: false,
isPdf: false,
isAudio: false,
isVideo: false,
isOffice