袁洪盛的个人博客
vue动态添加表单,并解决ElementUI多个图片上传Upload双向数据绑定的问题
发布于 2023年7月29日热度 1122
话不多说,直接上demo
<template>
<el-form>
<el-form-item label="案例">
<el-button @click="addFormElement('formElements')" size="small">添加一组</el-button>
<div v-for="(item, index) in formElements" :key="index" class="dynamicForms">
<div class="uploadImg">
<div class="imgItem">
<el-upload
class="avatar-uploader"
action="/upload"
name="static"
:show-file-list="false"
:on-success="(res) => { return handleAvatarSuccess(res, index,'formElements', 'imageUrl'); }"
:data-index="index"
>
<img v-if="item.imageUrl" :src="item.imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
<span></span>
</el-upload>
<span>封面图片</span>
</div>
<div class="imgItem">
<el-upload
class="avatar-uploader"
action="/upload"
name="static"
:show-file-list="false"
:on-success="(res) => { return handleAvatarSuccess(res, index,'formElements', 'imageUrl2'); }"
:data-index="index"
>
<img v-if="item.imageUrl2" :src="item.imageUrl2" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<span>预览大图</span>
</div>
<div class="input">
<el-input
v-model="item.title"
type="text"
placeholder="标题"
size="small"
/>
</div>
<div class="del" @click="handleDeleteDynamicForms('formElements',index)">删除该项</div>
</div>
</div>
</el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
formElements: [
{ value: "", imageUrl: "", imageUrl2: ""},
],
};
},
methods: {
// 图片上传成功
handleAvatarSuccess(res, index,fname, name) {
this[fname][index][name] = res.data.url;
},
//添加表单
addFormElement(name) {
this[name].push({
value: "",
imageUrl: "",
imageUrl2: "",
});
},
//删除表单
handleDeleteDynamicForms(name,index){
this[name].splice(index,1)
}
},
};
</script>
<style>
.uploadImg {
display: flex;
}
.dynamicForms {
margin-top: 15px;
}
.del{
margin-left: 20px;
color: #666;
cursor: pointer;
}
.del:hover{
color: red;
}
.imgItem {
margin-right: 15px;
}
.imgItem span {
text-align: center;
font-size: 14px;
color: #666;
display: block;
}
.avatar-uploader {
height: 120px;
}
.avatar-uploader .el-upload {
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;
width: 120px;
height: 120px;
line-height: 120px;
text-align: center;
}
.avatar {
width: 120px;
height: 120px;
display: block;
}
</style>