Vue3 + Element Plus实现用户粘贴图片上传功能的组件
<template>
<div>
<el-upload
:action="uploadAction"
:headers="uploadHeaders"
:on-success="handleSuccess"
:on-error="handleError"
:before-upload="beforeUpload"
ref="upload"
list-type="picture-card"
accept="image/*"
>
<i class="el-icon-plus"></i>
</el-upload>
<div v-if="imageUrl" class="uploaded-image">
<img :src="imageUrl" alt="上传的图片" />
</div>
</div>
</template>
<script>
import { ref } from 'vue';
import { ElMessageBox } from 'element-plus';
export default {
setup() {
const uploadAction = 'https://your-api.com/upload'; // 替换为你的上传API
const uploadHeaders = { Authorization: 'Bearer your-token' }; // 替换为必要的认证token
const imageUrl = ref(null);
const handleSuccess = (response, file, fileList) => {
imageUrl.value = URL.createObjectURL(file.raw);
};
const handleError = (err, file, fileList) => {
console.error('上传失败', err);
ElMessageBox.alert('上传失败,请重试', '错误', { type: 'error' });
};
const beforeUpload = (file) => {
const isImage = file.type.startsWith('image/');
if (!isImage) {
ElMessageBox.alert('只能上传图片', '错误', { type: 'error' });
}
return isImage;
};
return {
uploadAction,
uploadHeaders,
handleSuccess,
handleError,
beforeUpload,
imageUrl,
};
},
};
</script>
<style scoped>
.uploaded-image {
margin-top: 10px;
}
.uploaded-image img {
max-width: 100%;
}
</style>
这段代码提供了一个简单的Vue组件,用户可以通过粘贴图片或点击上传按钮来上传图片。图片上传成功后,会显示在组件内部。如果上传失败,会弹出错误提示。这个组件可以作为一个基本的参考实现,用户可以根据自己的需求进行相应的调整和扩展。
评论已关闭