问题描述:
在图片上传列表中,需要对图片上传的个数进行限制,在增加图片到最大数量限制时,就将上传框隐藏掉;在删除后,就再次显示出来;如果仅仅用 limit 是 可以实现功能的,但是会在后面发现下图最后面的框,还能选取文件,只是上传不了;
一、通过 limit 进行长度限制,设置 动态class 来进行显示和隐藏;
关键代码: :limit="limitCount" :class="{hide:hideUpload}"
<el-upload
action="#"
accept=".jpg, .jpeg, .png"
list-type="picture-card"
:auto-upload="false"
:on-change="handleChange"
:file-list="fileList"
:limit="limitCount"
:on-exceed="fileMaxNum"
:class="{hide:hideUpload}"
>
<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="handlePictureCardPreview(file)"
>
<i class="el-icon-zoom-in"></i>
</span>
<span
v-if="!disabled"
class="el-upload-list__item-delete"
@click="handleDownload(file)"
>
<i class="el-icon-download"></i>
</span>
<span
v-if="!disabled"
class="el-upload-list__item-delete"
@click="handleRemove(file)"
>
<i class="el-icon-delete"></i>
</span>
</span>
</div>
</el-upload>
<!-- 预览弹窗 -->
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
二、在文件上传和文件移除时,根据已经上传的列表的长度(length),对上传框进行显隐;
关键代码:this.hideUpload = this.fileList.length >= this.limitCount;
<script>
export default {
data() {
return {
dialogImageUrl: '',
dialogVisible: false,
disabled: false,
fileList: [], // 图片上传列表
hideUpload: false, // 是否隐藏上传框
limitCount:8, // 图片上传的数量限制
};
},
methods: {
// 上传
handleChange(file, fileList){
this.fileList = fileList;
this.hideUpload = this.fileList.length >= this.limitCount;
}
// 移除
handleRemove(file) {
console.log(file);
/*
移除文件,重新设置 fileList ,编写处理方法
this.fileList = ???
*/
this.hideUpload = this.fileList.length >= this.limitCount;
},
// 预览
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
// 下载
handleDownload(file) {
console.log(file);
},
}
}
</script>
三、通过样式来控制
这里有写 scoped,需要进行样式穿透 /deep/
<style lang="less" scoped>
/deep/.hide .el-upload--picture-card {
display: none;
}
</style>