編碼都是以需求爲導向的,因此編碼前必定要弄清楚須要的結果是什麼,而後再開始編碼。數組
如今簡單的說下需求:以下圖所示,點擊藍色的「+」按鈕,能夠連續生成多個圖片上傳框,每一個圖片上傳框都是單獨上傳圖片,編輯互不影響。dom
如今說下個人代碼實現過程:ui
element ui: <div class="form-right"> <div class="right_btns">轉帳匯款信息 <el-button type="primary" @click="addupload" v-if="adduploadShow">+</el-button> </div> <div class="upload_parent" v-if="uploadShow" v-for="(item, index) in datas_upload" :key="index"> <div class="defind_img_s"> <img :src="item.url" class="defind"> <el-upload :ref='"upload" + index' name="img_b" class="upload-demo" :action="uploadUrl" :headers="upload_hearder" :on-remove='handleRemove' :on-success='uploadSuc' :file-list='fileList' :show-file-list="false"> <div @click='getUploadTag(item, index)' class="up_btns">{{item.up_btn}}</div> </el-upload> <span v-show="item.upbtnGroup" class="upbtnGroups" @click="delupload(item,index)">刪除</span> </div> </div> </div>
data() { return { // 上傳成功後的id uploadId: '', // 從新上傳成功後的id resetUploadId: '', // upload控件tag uploadTag: 0, // 上傳圖片文件列表 fileList: [], upItem: {}, // 全部帳號-select accVal: '1', // 圖片上傳框初始數組 datas_upload: [{ up_btn: '上傳圖片', upbtnGroup: false, imgId: '', url: '' }],
// 圖片初始id數組 imgArryid: [], } }, methods: { // 點擊「+」按鈕生成圖片上傳框 addupload() { this.datas_upload.push({ up_btn: '上傳圖片', upbtnGroup: false, imgId: '', url: '' }) }, // 獲取圖片id getimgId() { for (var i = 0; i < this.datas_upload.length; i++) { this.imgArryid.push(this.datas_upload[i].imgId) } console.log(this.imgArryid, 785) return this.imgArryid }, // 圖片上傳 getUploadTag(item, index) { // console.log(response, file, fileList, 564) this.uploadTag = index console.log(index, 220) this.upItem = item }, // 圖片上傳成功 uploadSuc(response, file, fileList) { console.log(1230, response, response.id) console.log(file, fileList, 6630) // 把圖片id添加到 uploadId 數據中 this.datas_upload[this.uploadTag].imgId = response.id this.uploadId = response.id this.upItem.up_btn = '從新上傳圖片' this.upItem.upbtnGroup = true var imgs = 'imgs' + this.uploadTag console.log(this.$refs.imgs, 267) this.upItem.url = file.url }, // 上傳圖片-刪除 delupload(item, index) { console.log(index, 562) for (var i = 0; i < this.datas_upload.length; i++) { if (i != 0) { if (index == i) { this.datas_upload.splice(i, 1) this.datas_upload[index].imgId = '' } } else if (i == 0) { console.log(index, item, 563) this.datas_upload[index].imgId = '' this.datas_upload[index].url = '' item.up_btn = '上傳圖片' item.upbtnGroup = false } } }, // 從新上傳-success resetUploadSuc(response, file, fileList) { this.resetUploadId = response.id this.conResUploadView = false this.conRessubmitView = true } }
注意:像這種能夠生成多個數據的,首先想到使用數組的v-for循環遍從來實現,初始化默認有一個圖片上傳框,那就給數組一個初始化的對象,每當點擊按鈕就往數組中添加新的對象,利用數據的雙向綁定,便能生成相應的dom元素,達到想要的效果。this