el-upload 仅上传一张图片
1.el-upload组件使用
<el-upload action="#" list-type="picture-card"
:auto-upload="false"
:on-change="handleChange"
:limit='1'
:on-remove="handleRemove"
:file-list="imgFilesList " >
<i class="el-icon-plus" ></i>
</el-upload>
<!--
auto-upload 是否在选取文件后立即进行上传
on-change 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
on-remove 点击删除时的钩子
file-list 供回显的数据
limit 最大上传的个数
-->
通过以上操作可以控制只上传一张图片,但仍会显示
2.上传完将新增按钮隐藏起来
handleChange:function(file,fileList){
let that = this;
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
that.imgFilesList = [];
this.$message.error('上传头像图片大小不能超过 2MB!');
return isLt2M;
}else{
that.fileList = fileList;
}
// 当上传图片成功时,即隐藏上传按钮
if(fileList.length > 0){
$('.el-upload').css('display','none');
}
},
3.点击删除将新增按钮显示
handleRemove(file, fileList) {
this.fileList = []
if(fileList.length == 0){
$('.el-upload').css('display','inline-block');
}
}
4.会出现的问题
- 如果是在el-dialog中的弹框 由于dialog是懒渲染机制 导致无法选中元素问题
解决方案
// 点击显示弹框
dialogFun:function(index){
let that = this;
// that.List[index].logoFile 为回显数据中地址是否为空
if(that.List[index].logoFile != null){
// el-upload的回显方式
that.imgFilesList.push({name:'',url:that.List[index].logoFile});
setTimeout(function(){ //解决dialog弹窗第一次懒渲染 无法选中元素问题
$('.el-upload').css('display','none');
},0);
}else{
$('.el-upload').css('display','inline-block');
}
},