頁面結構,其中有其他屬性需要設置可前往element查看
<el-upload class="avatar-uploader" ref="upload" action="#" :show-file-list="false" :before-upload="beforeUpload" :on-success="handleChange" :on-change="onChange" :auto-upload="false" :data="addList"> <img v-if="imageUrl" :src="imageUrl" class="avatar" alt> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload>
js代碼,未定義的數據自行在data中定義
beforeUpload(){ const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上傳頭像圖片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上傳頭像圖片大小不能超過 2MB!'); } return isJPG && isLt2M; }, onChange(file,fileList){ var _this = this; var event = event || window.event; var file = event.target.files[0]; var reader = new FileReader(); //轉base64 reader.onload = function(e) { _this.imageUrl = e.target.result //將圖片路徑賦值給src } reader.readAsDataURL(file); }, handleChange(res, file) { this.imageUrl = URL.createObjectURL(file.raw); },
css樣式,摘自官方文檔
<style> .avatar-uploader .el-upload { border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; } .avatar-uploader .el-upload:hover { border-color: #409EFF; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; width: 178px; height: 178px; line-height: 178px; text-align: center; } .avatar { width: 178px; height: 178px; display: block; } </style>