根据elementui中的上传组件upload,手写一个编辑时回显上传文件以及继续新增文件的功能

elementui组件库非常强大,但是有的组件不一定是非常契合我们实际开发中的项目的,比如文件上传的功能。


大致图片.png

附件后台接口传参类型为string.png
1、表单上传附件
<el-form-item
        v-if="form.publishWay == 1 || !form.publishWay"
        class="img-item"
        label="通知附件"
        :label-width="formLabelWidth"
      >
        <el-upload
          ref="upload"
          class="upload-demo"
          :action="uploadImgUrl"
          :on-remove="handleRemove"
          show-upload-list
          multiple
          :on-success="uploadFileSuccess"
        >
          <el-button size="small" type="primary">点击上传附件</el-button>
        </el-upload>
        <div class="upload-file">
          <ul>
            <li
              @mouseenter="handleMouseEnter(item)"
              @mouseleave="handleMouseLeave(item)"
              class="upload-file-list"
              v-for="item in file"
              :key="item.filePath"
            >
              <i class="el-icon-document" style="marginright: 7px"></i>
              <span>{{ item.fileName }}</span>
              <i
                class="el-icon-close"
                @click="handleDelete(item)"
                :key="item.filePath"
                v-if="isHover && row.filePath == item.filePath"
              ></i>
            </li>
          </ul>
        </div>
      </el-form-item>

通过新增一个div盒子去展示提交到后台的表单附件列表,当打开表单弹窗时,附件列表区域初始化,这时使用upload自身的文件上传组件即可。

2、删除文件以及上传文件都要将文件的名称以及路径存入到数组中方便提交
    // 删除
    handleRemove(file, fileList) {
      // 删除文件时,对提交的文件列表再进一下筛选
      this.fileNamesList = [];
      this.filePathsList = [];
      fileList.forEach((item) => {
        this.fileNamesList.push(item.name);
        this.filePathsList.push(item.response.data.fileIds[0]);
      });
    },
    //上传图片成功
    uploadSuccess(response) {
      this.imgUrl = response.data.fileIds[0];
    },
    // 上传文件成功
    uploadFileSuccess(response, file, fileList) {
      this.fileNamesList = [];
      this.filePathsList = [];
      fileList.forEach((item) => {
        this.fileNamesList.push(item.name);
        this.filePathsList.push(item.response.data.fileIds[0]);
      });
    },
3、提交表单
    Object.assign(this.form, {
        coverImg: this.imgUrl,
        filePaths: this.filePathsList.join(),
        fileNames: this.fileNamesList.join(),
      });
        addQyNotice(this.form).then((res) => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "添加成功",
              duration: "1000",
            });
            this.$refs.upload.clearFiles();
            this.$emit("handleSuccess");
          }
        });
4、编辑时打开弹窗根据接口返回的详细数据进行回显

由于axios是异步请求数据,因此在同步操作时是存在问题的,需要对异步进行async处理。

4.1、使用async处理异步的问题
// 打开弹窗
    async handleOpen(row) {
      // 清空下载列表
      this.$nextTick(()=>{
        this.file = [];
        this.$refs.upload.clearFiles();
      })
      if (row) {
        this.title = "编辑通知";
        // 处理axios异步请求的数据
        try {
          await noticeDetail(row.id).then((res) => {
            if (res.code == 0) {
              this.form = res.data;
              this.form.sendFlag = this.form.sendFlag.toString();
              this.form.fileNames = this.form.fileNames.split(",");
              this.form.filePaths = this.form.filePaths.split(",");
              this.file = this.form.fileNames.map((fileName, i) => ({
                fileName,
                filePath: this.form.filePaths[i],
              }));
            }
          });
        } catch (error) {
          this.$message({
            type: "error",
            message: error,
            duration: "800",
          });
        }
        this.imgUrl = this.form.coverImg;
      } else {
        this.form = {};
        this.imgUrl = false;
        this.title = "新增通知";
      }
      this.dialogVisible = true;
    },
4.2、文件回显后删除已上传的文件操作
4.2.1、当鼠标悬浮到已上传的文件区域时,添加icon图标
    // 鼠标悬浮事件
    handleMouseEnter(row) {
      this.row = row;
      this.isHover = true;
    },
    handleMouseLeave(row) {
      this.row = row;
      this.isHover = false;
    },
4.2.2、删除已上传的文件
    // 编辑时删除已上传的文件
    handleDelete(row) {
      // 已上传的文件删除
      this.file = this.file.filter((el) => {
        if (el.filePath !== row.filePath) {
          return el;
        }
      });
    },
4.3、编辑完成后提交修改后的表单数据

根据后台的传参要求将已上传的文件信息做字符串拼接到新上传的文件的字符串后面为一个编辑后的文件信息,然后把整个字符串传给后台。

 // 处理已上传的文件做字符串拼接到新上传的文件的字符串后面
        let pushFilePaths = this.file.map((item) => {
          return item.filePath;
        }).join(',');
        let pushFileNames = this.file.map((item) => {
          return item.fileName;
        }).join(',');
        let form = {
          title: this.form.title,
          coverImg: this.form.coverImg,
          brief: this.form.brief,
          content: this.form.content,
          filePaths: this.form.filePaths + "," + pushFilePaths,
          fileNames: this.form.fileNames + "," + pushFileNames,
          noticeCategory: this.form.noticeCategory,
          id: this.form.id,
          publishWay: this.form.publishWay,
          linkUrl: this.form.linkUrl,
        };
        editQyNotice(form).then((res) => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "编辑成功",
              duration: "1000",
            });
            this.$refs.upload.clearFiles();
            this.$emit("handleSuccess");
          }
        });
4.4、将两个数组合并为一个对象数组
this.form.fileNames = this.form.fileNames.split(",");
this.form.filePaths = this.form.filePaths.split(",");
this.file = this.form.fileNames.map((fileName, i) => ({
      fileName,
      filePath: this.form.filePaths[i],
}));
4.5、回显展示已上传附件的盒子的css样式
.upload-file-list {
  color: #606266;
  display: flex;
  align-items: center;
  margin-right: 40px;
  height: 25px;
  width: 100%;
  margin-top: 5px;
  line-height: 25px;
  padding-left: 4px;
  -webkit-transition: color 0.3s;
  transition: color 0.3s;
}
.upload-file-list > span {
  margin-left: 7px;
  width: 90%;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.upload-file-list:hover {
  background-color: #f5f7fa;
}
.upload-file-list:hover > span {
  color: #409eff;
  cursor: pointer;
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 156,757评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,478评论 1 289
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,540评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,593评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,903评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,329评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,659评论 2 309
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,383评论 0 195
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,055评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,337评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,864评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,227评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,820评论 3 231
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,999评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,750评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,365评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,260评论 2 258

推荐阅读更多精彩内容