<el-upload :action='接口路徑' :show-file-list='false' name='img' //接口需要傳的圖片字段 可以直接在這定義 :with-credentials='true //支持發送 cookie 憑證信息 :on-success='handleAvatarSuccess' :before-upload='beforeAvatarUpload' > <img v-if='imageUrl' :src='imageUrl'/> //這里渲染根據接口拿到的圖片路徑 需在data中定義imageUrl <i v-else class='elicon-plus avatar-uploader-icon'></i> </el-upload>
handleAvatarSuccess(res){ if(res.code==1){ //這里根據接口返回的去判斷 this.imageUrl = res.data.img_path //拿到圖片的路徑 } }
//限制上傳時的文件格式大小
beforeAvatarUpload(file) {
const isJPG = file.type === "image/jpeg" || file.type === "image/png";
const isLt2M = file.size / 1024 / 1024 < 3;
if (!isJPG) {
this.$message.error("上傳圖片只能是 JPG 和 Png 格式!");
return false;
}
if (!isLt2M) {
this.$message.error("上傳圖片大小不能超過 3MB!");
return false;
}
},