openks / learn-vue

自定义组件文档
https://openks.github.io/learn-vue
0 stars 0 forks source link

20180313_论el-upload的正确使用方法 #85

Open openks opened 6 years ago

openks commented 6 years ago

<el-upload>的正确使用方法
表单里有上传控件
看遗留代码是这么用的

<el-form :model="ruleForm"
         ref="ruleForm">
    <el-form-item label="上传文件">
        <el-upload class="upload-demo"
                   :on-success="successUpload"
                   :action="mixinUploadUrl"
                   :on-remove="handleRemove"
                   :file-list="fileList">
            <el-button size="small"
                       type="primary">点击上传</el-button>
        </el-upload>
    </el-form-item>
    <el-form-item>
        <el-button type="primary"
                   @click="submitForm('ruleForm')">导出</el-button>
    </el-form-item>
</el-form>
<script>
export default {
  data () {
      return {
          fileList: [],
          ruleForm: {
              fileList: []
          },
      }
  },
  methods: {
    handleRemove (file, fileList) {
        // 删除时在表单的某个字段里移除一个值
        let tmp = this.ruleForm.fileList
        let url = file.response.result[0].url
        if (tmp.includes(url)) {
            tmp.splice(tmp.findIndex(item => {
                return item === url
            }), 1)
        }
    },
    successUpload (response, file, fileList, $event) {
      // 上传成功在表单的某个字段里加一个值
        this.ruleForm.fileList.push(file.response.result[0].url)
    },
    submitForm (formName) {
        let fileList = this.ruleForm.fileList
        // 使用fileList与服务端交互 该字段只包含服务端数据
    },
  }
}
</script>

其实successUploadhandleRemove没有必要使用,只需要在提交的时候获取到已经上传到服务端的文件相关信息(如服务端保存路径,唯一标识等)即可

观察fileList在文件上传前后没有任何变化,说明该字段不是动态的
推测应该有个字段保存着服务端返回数据列表仔细查看后发现的确如此
其实el-upload组件有个属性uploadFiles是会根据上传文件结果进行动态处理的,上传成功增加一个移除掉一个,提交表单时只需要处理该字段即可

更好的使用流程如下:

<el-form :model="ruleForm"
         ref="ruleForm">
    <el-form-item label="上传文件">
        <el-upload ref="uploada"
                   :action="mixinUploadUrl"
                   :file-list="fileList">
            <el-button size="small"
                       type="primary">点击上传</el-button>
        </el-upload>
    </el-form-item>
    <el-form-item>
        <el-button type="primary"
                   @click="submitForm('ruleForm')">导出</el-button>
    </el-form-item>
</el-form>
<script>
export default {
  data () {
      return {
          fileList: [],
      }
  },
  methods: {
    submitForm (formName) {
        //包含上传的文件信息和服务端返回的所有信息都在这个对象里
        this.$refs.uploada.uploadFiles
    },
  }
}
</script>