vue 实现在线预览
Vue 实现在线预览功能
在线预览功能通常用于查看文档、图片、PDF等文件内容,无需下载即可直接浏览。以下是几种常见的实现方式:
使用 iframe 嵌入预览
<template>
<iframe :src="fileUrl" width="100%" height="500px"></iframe>
</template>
<script>
export default {
data() {
return {
fileUrl: 'https://example.com/document.pdf'
}
}
}
</script>
PDF 文件预览
安装 pdf.js 或 vue-pdf 库:
npm install vue-pdf
使用示例:
<template>
<pdf :src="pdfUrl" style="width: 100%; height: 800px;"></pdf>
</template>
<script>
import pdf from 'vue-pdf'
export default {
components: { pdf },
data() {
return {
pdfUrl: '/documents/sample.pdf'
}
}
}
</script>
Office 文档预览

使用微软 Office Online 预览服务:
<template>
<iframe
:src="'https://view.officeapps.live.com/op/embed.aspx?src=' + encodeURIComponent(fileUrl)"
width="100%"
height="500px">
</iframe>
</template>
图片预览
使用内置的 img 标签或第三方组件:
<template>
<img :src="imageUrl" style="max-width: 100%; max-height: 80vh;">
</template>
视频预览

使用 HTML5 video 标签:
<template>
<video controls width="100%">
<source :src="videoUrl" type="video/mp4">
</video>
</template>
文件上传即时预览
对于用户上传的文件,可以使用 FileReader API 实现即时预览:
<template>
<input type="file" @change="previewFile">
<img v-if="previewImage" :src="previewImage" style="max-width: 300px;">
</template>
<script>
export default {
data() {
return {
previewImage: null
}
},
methods: {
previewFile(event) {
const file = event.target.files[0]
if (!file) return
const reader = new FileReader()
reader.onload = (e) => {
this.previewImage = e.target.result
}
reader.readAsDataURL(file)
}
}
}
</script>
注意事项
- 跨域问题需要正确处理,特别是使用 iframe 时
- 大文件预览需要考虑性能优化
- 敏感文件需要做好权限控制
- 移动端需要适配不同屏幕尺寸






