vue3+ts - element-plus封装上传文件图片组件
warning:
这篇文章距离上次修改已过186天,其中的内容可能已经有所变动。
<template>
<el-upload
:action="uploadUrl"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:headers="headers"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { ElUpload, ElDialog } from 'element-plus';
export default defineComponent({
components: {
ElUpload,
ElDialog
},
setup() {
const uploadUrl = 'https://jsonplaceholder.typicode.com/posts/'; // 替换为你的上传地址
const headers = { Authorization: 'Bearer your-token' }; // 替换为你的请求头
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const handleRemove = (file: any, fileList: any) => {
console.log(file, fileList);
};
const handlePictureCardPreview = (file: any) => {
dialogImageUrl.value = file.url;
dialogVisible.value = true;
};
const handleSuccess = (response: any, file: any, fileList: any) => {
console.log(response, file, fileList);
};
const beforeUpload = (file: any) => {
const isJPG = file.type === 'image/jpeg';
const isLT2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
ElMessage.error('上传头像图片只能是 JPG 格式!');
}
if (!isLT2M) {
ElMessage.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLT2M;
};
return {
uploadUrl,
headers,
dialogImageUrl,
dialogVisible,
handleRemove,
handlePictureCardPreview,
handleSuccess,
beforeUpload
};
}
});
</script>
这个例子展示了如何在Vue 3和TypeScript中使用Element Plus创建一个简单的上传图片组件。它包括了上传图片的基本功能,例如预览、删除和上传成功后的处理。同时,它也包括了文件类型和大小的验证,以确保只有符合条件的图片文件能被上传。
评论已关闭