最近有个后台管理项目要实现上传图片功能,然后呢我就用Element组件实现了这个功能
action属性是要结合你接口文档的上传图片,不然你是上传空白的
下面是整体代码:
<template>
<div>
<p>商品图片:</p>
<div class="commodity_img">
<!-- 上传图片 -->
<el-upload
list-type="picture-card"
:action="'/pcapi/File/fileimg'"
:on-change="handleChange"
:before-remove="beforeRemove"
:on-preview="handlePictureCardPreview"
:file-list="fileList"
multiple
limit="1"
name="img"
>
<el-icon class="avatar-uploader-icon">
<Plus />
</el-icon>
</el-upload>
</div>
</div>
</template>
<script setup>
import { Plus } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
// 上传图片
const fileList = ref([]);
//上传文件
const handleChange = (file: {
status;
response: { front_file };
}) => {
if (file.status == "success") {
fileList.value.push({ url: file.response.front_file });
}
// console.log(fileList.value);
};
// 删除
const beforeRemove = () => {
const result = new Promise((resolve, reject) => {
ElMessageBox.confirm("此操作将删除该图片, 是否继续?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
})
.then(() => {
resolve();
})
.catch(() => {
reject(false);
});
});
return result;
};
// 单张图片和多张图片预览
const handlePictureCardPreview = (uploadFile: { url }) => {
dialogImageUrl.value = uploadFile.url;
dialogVisibles.value = true;
};
</script>