Open openks opened 6 years ago
需求:实现一个自定义文件上传组件
实现思路:
原思路:
具体细节:
面对回填问题时想到方案:
<template> <div class="upload-new"> <div class="add" @click="uploadClick"> <i class="iconfont icon-add"></i> </div> <div v-for="(file, i) in allfiles" class='imgwrap' :key="i"> <img :src="/file/'+file.name" class="imgg"> <span @click="delFile(file.uploadFileId)" class="delete"> <i class="iconfont icon-delete"></i> </span> </div> <input ref="upload" type="file" :multiple="multiple" hidden @change="uploadFile" /> </div> </template> <script> import { Indicator, Toast } from 'mint-ui'; export default { name: 'upload-file-new', props: { multiple: { default: false, }, defaultFiles: { type: Array, default: function() { return []; }, }, }, watch: { defaultFiles() { this.dfiles = this.defaultFiles; }, }, computed: { allfiles() { return this.dfiles.concat(this.files); }, }, data() { return { files: [], dfiles: [], }; }, methods: { uploadClick(val) { this.$refs.upload.click(); }, uploadFile(evt) { let items = evt.target.files; if (items.length > 0) { let formData = new FormData(); let url = 'file/fileUpload'; for (let i = 0; i < items.length; i++) { formData.append('file', items[i]); } Indicator.open({ text: '文件上传中...', spinnerType: 'fading-circle', }); this.axios .post(url, formData) .then(res => { Indicator.close(); if (res.data.code === '20000') { let results = res.data.result; for (let i = 0; i < results.length; i++) { this.files.push(results[i]); } this.$emit('gotFile', this.allfiles); } else { Toast('文件上传失败'); } }) .catch(err => { Indicator.close(); Toast('文件上传异常,请联系管理员'); console.error(url, err); }); } else { console.log('ddddddddd'); } }, delFile(uploadFileId) { // 删除的是本次上传的 let index = this.files.findIndex( ele => ele.uploadFileId === uploadFileId, ); if (index > -1) { this.files.splice(index, 1); } let index2 = this.dfiles.findIndex( ele => ele.uploadFileId === uploadFileId, ); if (index2 > -1) { this.dfiles.splice(index, 1); } console.log('index', index, uploadFileId, this.allfiles); this.$emit('gotFile', this.allfiles); }, }, }; </script> <style lang="less"> .upload-new { .add, .imgg { width: 60px; height: 60px; margin: 5px 0; border: 1px solid #d9d9d9; } .add { float: left; margin-right: 10px; } .icon-add { font-size: 62px; color: #d9d9d9; } .delete { position: absolute; right: 5px; top: 10px; width: 16px; height: 16px; display: block; background-color: #26a2ff; color: #fff; text-align: center; } .imgwrap { float: left; margin-right: 10px; position: relative; } } </style>
需求:实现一个自定义文件上传组件
轻松进行文件回填
实现思路:
原思路:
具体细节:
面对回填问题时想到方案: