Vue 图片上传并浏览器实时预览
<template>
<div>
<input type='file' @change='handleFileUpload'>
<img v-if='imageUrl' :src='imageUrl' alt='Uploaded image'>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: null
};
},
methods: {
handleFileUpload(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
this.imageUrl = reader.result;
};
}
}
};
</script>
<p>在上面的代码中,我们首先创建了一个包含一个文件上传输入框和一个图片元素的 Vue 组件。当用户选择一个文件时,我们会通过<code>handleFileUpload</code>方法读取文件并将其转换为 DataURL。最后,我们将 DataURL 赋值给<code>imageUrl</code>变量,并在页面上显示图片。</p>
原文地址: http://www.cveoy.top/t/topic/oAro 著作权归作者所有。请勿转载和采集!