Ant Design Vue - <a-upload> 文件上传回显及清空文件

前言

本文提供一个示例,请根据项目需求进行改造。

当用户上传完文件关闭页面后,再次打开编辑后需要 回显 出来,

并且还能清空,如下图所示:
在这里插入图片描述

解决方案

示例环境:Vue2 / Ant Design Vue 2 ,只保留了核心功能,没有任何校验,如有需要自行添加。

在项目中建立一个干净的页面,复制并运行以下代码:

<template>
  <section>

    <!-- 上传组件 -->
    <a-upload
    action="https://jsonplaceholder.typicode.com/posts/"
    :file-list="fileList"
    :remove="handleRemove"
    :before-upload="beforeUpload"
    :default-file-list="defaultFileList"
    >
        <a-button>
            <a-icon type="upload" />
            点击上传附件
        </a-button>
    </a-upload>
    <!-- END -->

    <!-- 操作(根据业务逻辑调用) -->
    <hr>
    <button @click="edit()">已上传文件回显</button>
    <button @click="resetFiles()">清空</button>
    <!-- END -->

    <!-- 信息 -->
    <hr>
    <p>文件列表:{
   
   { fileList}}</p>
    <p>已上传列表: {
   
   { defaultFileList }}</p>
    <!-- END -->
    
  </section>
</template>


<script>
export default {
      
      
  data() {
      
      
	  return {
      
      
      fileList: [],//文件列表
      defaultFileList: [],//默认已上传的列表(编辑回显)
	  }
  },
  
  methods: {
      
      

    // 文件上传方法
    handleRemove(file) {
      
      
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      
      
      this.fileList = [...this.fileList, file];
      return false;
    },

    // 清空文件列表及已上传列表
    resetFiles: function() {
      
      
        this.fileList = []
        this.defaultFileList = []
    },

    // 已上传文件回显
    edit() {
      
      
      // 文件
      const d = {
      
      
        uid: '1',
        name: '示例(替换为从服务端返回的文件)',
        status: 'done',
      }

      // 文件列表
      this.fileList.push(d)
      
      // 已上传列表
      this.defaultFileList.push(d)
    },

  }
}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_44198965/article/details/124272472
今日推荐