1.結(jié)構(gòu)
<template>
<el-row>
<el-col :span="24">
<el-form
:model="addForm"
:rules="rules"
ref="addForm"
status-icon
label-width="130px"
class="demo-ruleForm">
<div class="form_upload">
<el-upload
class="avatar-uploader"
action="你要必選參數(shù),上傳的地址"
:show-file-list="false" // 是否顯示已上傳文件列表 類型為:true或者false
:on-success="handleAvatarSuccess" // 文件上傳成功時的鉤子function(response, file, fileList) 類型為:一個函數(shù)里面有要帶的三個參數(shù)
:before-upload="beforeAvatarUpload"> // 上傳文件之前的鉤子,參數(shù)為上傳的文件芦圾,若返回 false 或者返回 Promise 且被 reject绿店,則停止上傳。類型為:function(fileList)
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<span class="upload_span">支持大小不超過2M的JPG,GIF,PNG圖片上傳</span>
</div>
<el-col :span="24" class="form_bottom">
<el-form-item>
<el-button type="primary" @click="submitForm('addForm')"> 確 定 </el-button>
<el-button @click="resetForm('addForm')"> 取 消 </el-button>
</el-form-item>
</el-col>
</el-form>
</el-col>
</el-row>
</template>
2.行為
export default {
data(){
return{
// form表單里綁定的數(shù)據(jù)
addForm:{
headImg: "", // 上傳頭像
}赔癌,
// 頭像上傳
editHeadImgUrl:"向后臺請求的URL",
// 頭像上傳
imaegUrlId:'',
imageUrl: '',
imageData: {
deviceType:"",
id:""
},
},
methods:{
// 提交
submitForm(formName) {
let _this = this;
let tempObject = this.addForm;
tempObject.headImg = this.imageId;
let NewpartyForm = JSON.stringify(tempObject);
this.$http.post(
this.creatPartyMemberUrl,
NewpartyForm
).then(
(res) => {
var success = res.data.success;
var msgMsg = res.data.message;
if (success) {
_this.$message("創(chuàng)建成功");
this.$router.push('PartyMemberList');
}
else {
_this.$message.error(msgMsg + "請檢查輸入內(nèi)容!");
}
console.log(res);
}
);
},
//上傳獲取ID
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
this.imageId=res.data.id;
this.addForm.headImg=res.data.id;
this.imaegUrlId=res.data.id;
},
// 上傳
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上傳頭像圖片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上傳頭像圖片大小不能超過 2MB!');
}
return isJPG && isLt2M;
},
}
-
樣式:
<style coped> /* 上傳頭像樣式 */ .avatar-uploader .el-upload {width: 100%; border: 1px dashed #d9d9d9;border-radius: 6px;cursor: pointer; position: relative; overflow: hidden;} .avatar-uploader .el-upload:hover {border-color: #409EFF;} .avatar-uploader-icon {font-size: 28px; color: #8c939d;line-height: 178px; text-align: center;} .avatar {width: 100%;height: 230px; display: block;} .avatar-uploader{padding: 10px;width: 80%;/* border: 1px solid #8c939d; */text-align: center;margin-left: 15px;} .form_upload{height: 284px;} .upload_span{font-size: 14px; color: #e4e4e4; display: block; padding: 10px;text-align: center;line-height: 20px;} </style>