//先上代碼
<template> <!-- data綁定的參數 getuploadloge: [ { url: '', name: '' } ], --> <!-- 編輯操作模板 this.uploadstatue = false //在父類給該upload組件添加v-if事件 this.$nextTick(() => { this.uploadstatue = true }) this.form = res.data //給upload傳參 this.getuploadloge = [ { name: res.data.Name, url: res.data.Logo, status: 0 } ] --> <!-- 新增模板 this.uploadstatue = false //在父類給該upload組件添加v-if事件 this.$nextTick(() => { this.uploadstatue = true }) //給upload傳參 this.getuploadloge[0].name = '' this.getuploadloge[0].url = '' this.getuploadloge[0].status = 1 -->
<!--上邊的添加事件是在父類引用改子類的標簽里加v-if事件,來保證組件從新加載,否則組件不會刷新--> <div> <p > 只能上傳jpg/png文件,且不超過1024kb </p> <el-upload action="#" :auto-upload="false" :file-list="fileList" :multiple = "false" :limit="1" accept=".jpg,.jpeg,.png" list-type="picture-card" :class="{hide:hideUpload}" :on-change="maximg" :before-upload="beforeAvatarUpload" :on-remove="handleRemove"> <!-- <img :src="backimg"> --> <i class="el-icon-plus"></i> </el-upload> </div> </template> <script> export default { props: ['getuploadloge'], data() { return { hideUpload: false, //隱藏添加窗口 dialogVisible: false, //照片模態框 fileList: [], //圖片數組 uploaddate: [], //子組件數組 backimg: '../../../static/images/bank_upload_logo.png' } }, mounted() { //獲取圖片數據 this.getupload() }, methods: { //獲取文件數據 getupload() { this.uploaddate = Object.assign(this.getuploadloge) if (this.uploaddate[0].status === 1) { this.fileList.length = 0 this.handleRemove('', this.fileList) } else { if (this.uploaddate[0].name) { this.fileList = this.uploaddate this.hideUpload = this.fileList.length >= 1 } } }, //文件列表移除文件時的鈎子 handleRemove(file, fileList) { if ((fileList.length = 0)) { this.hideUpload = true } else { this.hideUpload = fileList.length >= 1 this.$emit('uploaddate', '') } }, handlePictureCardPreview(file) {}, //文件狀態改變時的鈎子,添加文件、上傳成功和上傳失敗時都會被調用 maximg(file, fileList) { const isIMAGE = file.name.substring(file.name.lastIndexOf('.') + 1) const isLt1M = file.size / 1024 / 1024 if (isIMAGE !== 'jpg' && isIMAGE !== 'png' && isIMAGE !== 'jpeg') { this.$message.error('上傳文件只能是jpg和png格式!') this.fileList.length = 0 this.handleRemove(file, fileList) } if (isLt1M > 1) { this.$message.error('上傳文件大小不能超過 1MB!') this.fileList.length = 0 this.handleRemove(file, fileList) } this.hideUpload = fileList.length >= 1 let reader = new FileReader() //html5讀文件 //轉BASE64 reader.readAsDataURL(file.raw) reader.onload = e => { this.uploaddate = e.target.result //讀取完畢后調用接口 this.$emit('uploaddate', this.uploaddate) } return isIMAGE && isLt1M }, beforeAvatarUpload(file, fileList) { // console.log('123465789') } }, name: 'Upload' } </script> <style> .hide .el-upload--picture-card { display: none; } </style> <style scoped> </style>
//因為我的dialog寫的公用組件,需要的可以看下我的其他文章.
//因為我的新增與修改是一個模態框,所以判斷那一塊可以自行修改.
//file-list綁定的數組格式是:File-list:[{name:名字,url:地址}]
//只要符合這個數組就可以回顯.
//其中的屬性代表什么官網里有詳細解釋,在這里就不一一解釋了.
//說幾個特殊點的.accept屬性是點擊上傳按鈕后,彈出的圖片選擇框的默認后綴.目的是為了加載迅速,如果不加此屬性,點擊后頁面文件過多的情況下會加載很慢.
//注意:accept后面跟的不是驗證,accept后面跟的不是驗證,accept后面跟的不是驗證,如果需要驗證請在方法中寫校驗規則