element-ui图片上传组件查看和限制方式
作者:TianNicholas
这篇文章主要介绍了关于element-ui图片上传组件查看和限制方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
element-ui图片上传组件查看和限制
element-ui经常遇到图片上传,然后编辑查看限制上传个数和上传提示
- 1、limit上传个数限制配合on-exceed属性使用
- 2、上传之前提示图片大小限制属性before-upload
- 3、上传带参数data
- 4、上传成功on-success和移除on-remove
- 5、file-list属性展示的列表数组,查看也是设置这个
html的代码
<el-upload :limit="1" :on-exceed="config.exceed" ref="upload" class="upload-demo" :before-upload="config.onBeforeUpload" :on-success="config.handleAvatarSuccess" :data="config.dataParam" :action="config.actionUrl" :on-remove="config.handleRemove" :file-list="config.fileList2" //保存当前图片对象数组 :multiple="false" :show-file-list="true" list-type="picture"> <el-button size="small" type="primary">点击上传</el-button> </el-upload>
配置信息js 代码
config: {
dataParam: {
bizType: 3,
useType: 2
},
actionUrl: 'api/base-fdfs/fdfs/public/upload',
exceed:()=>{
this.$alert('请删除后再上传', '异常提示', {
confirmButtonText: '确定',
type: 'warning'
});
},
handleRemove: (file,fileList) => {
this.form.picture=''
this.config.fileList2=[] //删除此数组内的图片对象
},
onBeforeUpload: (file) => {
const isIMAGE = ((file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/bmp'));
if (!isIMAGE) {
this.$alert('上传文件只能是图片格式(jpeg/png/bmp)', '异常提示', {
confirmButtonText: '确定',
type: 'warning'
});
return false
}
if(file.size/1024/1024>5){
console.log(file.size)
this.$alert('图片不能大于5M', '异常提示', {
confirmButtonText: '确定',
type: 'warning'
});
return false
}
return true
},
handleAvatarSuccess: (res, file) => {
this.form.repairImages = file.response.data
},
fileList2: [],
},查看的时候还需给file-list数组设置,展示图片
let obj={}
this.config.fileList2=[]
this.$set(obj,'name','file');
this.$set(obj,'url',response.data.picture);
this.config.fileList2.push(obj) 清除文件列表,上传组件变初始状态
this.$refs.upload.clearFiles() //清除图片
element-ui限制一张图片上传

需求描述
在做图片上传组件的时候 有时候需求回要求只能上传一张图片
bug:element-ui在上传完一张图片后上传按钮还会存在 虽然可以用自带的limt属性加以限制 但是上传按钮依然会存在 且存入数组的值依然会增加

解决
可以判断上传后数组的length来控制图片上传的样式 让其上传一张后隐藏上传按钮 达到控制图片上传的数量需求
<el-form-item label="礼包主图" prop="goodsimage" :required="true">
<el-upload
:class="{ disabled: uploadDisabled }" //这里动态控制样式
:limit="1"
ref="picUpload"
class="pic-div"
action="'xxxxxxx'"
:with-credentials="true"
list-type="picture-card"
:on-remove="removePic"
:on-change="handleEditChange"
:file-list="goodsimage"
:on-exceed="beyond"
>
<div class="el-upload file-upload-container" @click.stop="popFileUpload('0')">
<i class="el-icon-plus"></i>
</div>
</el-upload>
</el-form-item>
// 隐藏图片上传按钮
uploadDisabled() {
return this.goodsimage.length > 0 //判断图片上传的数量动态控制按钮隐藏与显示
},
<style>
.disabled .el-upload--picture-card {
display: none;
}
</style>
最终效果


礼包视频也是如此要求仅限上传1个视频 由于是button按钮 俺就直接使用v-if判断视频的length来控制视频上传按钮的显示与隐藏
<el-button ***v-if="this.goodsvideo.length < 1"*** class="file-upload-btn-container" @click.stop="popFileUpload('1')" size="small" type="primary">点击上传</el-button >
上传视频后按钮隐藏

em…
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
