vue相较于js更加便利,尤其是其提供的组件;
今天分享一个vue3的图片上传组件
import { ElMessageBox } from "element-plus";
先引入组件;先看html部分
<el-upload list-type="picture-card" :action="'https://*******'"//接口 :on-change="handleChange" :before-remove="beforeRemove" :on-preview="handlePictureCardPreview" :file-list="fileList.front_file" multiple limit="1"//限制上传数量 name="img"//参数 > <el-icon class="avatar-uploader-icon"> <Plus /> </el-icon> </el-upload>
接下来是js部分
// 上传图片 const fileList = ref([]); const handleChange = file => { if (file.status == "success") { fileList.value = []; fileList.value.push(file.response); console.log(fileList); console.log(fileList.value[0].front_file); } }; // 删除 const beforeRemove = () => { const result = new Promise((resolve, reject) => { ElMessageBox.confirm("此操作将删除该图片, 是否继续?", "提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }) .then(() => { resolve(); upload_btn.value = false; }) .catch(() => { reject(false); }); }); return result; };
看看效果
因为我只需要上传一张所以加了一个限制,上传成功之后隐藏上传按钮
在html中放入
:class="{ hide_box: upload_btn }" :on-success="handleSuccess"
在js中声明
const upload_btn = ref(false);
最后在css中放入
.hide_box /deep/ .el-upload--picture-card { display: none; }