// Vue 实现文件预览功能示例代码
<template>
<div>
<input type="file" @change="handleFileChange" />
<div v-if="previewUrl">
<img v-if="isImage" :src="previewUrl" alt="Preview" />
<embed v-else :src="previewUrl" type="application/pdf" width="100%" height="600px" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
previewUrl: null,
isImage: false
};
},
methods: {
handleFileChange(event) {
const file = event.target.files[0];
if (file) {
this.isImage = file.type.startsWith('image/');
this.previewUrl = URL.createObjectURL(file);
}
}
}
};
</script>
<style scoped>
/* 样式可以根据需要自行添加 */
</style>
模板部分 (<template>):
<input type="file">) 和一个用于显示预览的 <div>。handleFileChange 方法。脚本部分 (<script>):
previewUrl 用于存储文件的预览 URL,isImage 用于判断是否为图片文件。handleFileChange 方法:isImage。URL.createObjectURL 创建文件的临时 URL 并赋值给 previewUrl。样式部分 (<style scoped>):
下一篇:vue3.0生命周期
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站