方法一:
原理:调用<el-upload>组件的方法唤起选择文件事件
效果:
页面代码:
1、选择图片按钮
<div class="flex_row_spacebetween btn" @click="chooseImg">
<span class="el-icon-plus ic-plus-sign"></span>
<span style="font-size: 13px;">更换票种图片</span>
</div>
2、展示选择的图片
<div>
<el-upload
ref="piaoTypeDialogUpload"
class="piao-type-dialog-upload"
action="#"
:limit="2"
:file-list="dialogform.img_files"
list-type="picture-card"
:auto-upload="false"
:before-upload="beforeAvatarUpload"
:on-change="piaoTypePicChange"
accept=".png,.jpg">
<i slot="default" class="el-icon-plus" ></i>
<div slot="file" slot-scope="{file}">
<img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
<span class="el-upload-list__item-actions">
<span class="el-upload-list__item-preview" @click="picShow(file)">
<i class="el-icon-zoom-in"></i>
</span>
<span class="el-upload-list__item-delete" @click="picDel('dialogform',file)">
<i class="el-icon-delete"></i>
</span>
</span>
</div>
</el-upload>
</div>
js代码:(其他逻辑与element文档的上使用一致)
chooseImg(){
this.$refs['piaoTypeDialogUpload'].$refs['upload-inner'].handleClick()
},
css代码:
隐藏原来的选择图片按钮
.piao-type-dialog-upload .el-upload-list--picture-card .el-upload-list__item {
width: 90px;
height: 90px;
}
.piao-type-dialog-upload .el-upload--picture-card {
display: none;
}
方法二:
原理:把图片显示分离出来,<el-upload>做选择图片使用,单独做一个显示图片的区域
效果:
页面代码:
1、选择文件按钮
<div>
<el-upload
action="#"
accept="image/*"
:on-change="(file)=>picChange(file,item)"
:show-file-list="false"
:multiple="item.multiple"
:before-upload="beforeAvatarUpload"
:auto-upload="false">
<div>
<i class="el-icon-plus" style="color: #FF4C15;"></i>
<span style="color: #FF4C15;">上传</span>
</div>
</el-upload>
</div>
2、显示图片区域
<div class="imglist" v-if="item.file_list.length != 0">
<div class="img-item" v-for="(img,index) in item.file_list" :key="item.pic_id">
<img :src="img.url" class="hover" alt="" style="width: 100%;height:100%">
3、预览图片,删除图片按钮
<span class="el-upload-list--picture-card">
<span class="el-upload-list__item-actions">
<span class="el-upload-list__item-preview" @click="picShow(img)">
<i class="el-icon-zoom-in"></i>
</span>
<span class="el-upload-list__item-delete" @click="zizhiPicDel(typeIndex+1,img)">
<i class="el-icon-delete"></i>
</span>
</span>
</span>
</div>
</div>
js 代码:
picChange(file,item){
item.file_list.push({
pic_id: xxxx,
url: xxxx, // 图片地址,就如何从file里获取图片地址(可能你选择图片就上传到服务器了,这时候放的就是服务器返回的地址)
});
}
css代码:
.imglist{
display: flex;
flex-wrap: wrap;
}
.imglist .img-item{
width:120px;
height:120px;
margin-right: 15px;
margin-top: 15px;
}
总结
两个方法的代码量都差不多,看自己的逻辑偏向哪个转得快一点。方法二还需要自己写上删除图片的东西。方法一,图片放大删除都用elementui文档说明里就可以了