代码
<template>
<el-dialog :visible.sync="dialogVisible" title="选择图片" width="50%">
<el-upload
class="upload-demo"
:action="actionUrl"
:headers="headers"
:data="{ token: token }"
:on-success="handleSuccess"
:on-error="handleError"
:on-remove="handleRemove"
:file-list="fileList"
:auto-upload="false"
:before-upload="beforeUpload"
:limit="limit"
:accept="accept"
:multiple="multiple"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传{{ limit }}个文件,且不超过 {{ size }} MB</div>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="handleConfirm">确 定</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
name: 'ImageSelector',
props: {
actionUrl: String,
headers: Object,
token: String,
limit: {
type: Number,
default: 1
},
size: {
type: Number,
default: 10
},
accept: {
type: String,
default: 'image/*'
},
multiple: {
type: Boolean,
default: false
},
defaultList: {
type: Array,
default: () => []
}
},
data() {
return {
dialogVisible: false,
fileList: []
}
},
methods: {
handleConfirm() {
this.$emit('confirm', this.fileList)
this.dialogVisible = false
},
handleSuccess(response, file, fileList) {
this.fileList = fileList
},
handleError(err, file, fileList) {
this.$message.error('上传失败')
},
handleRemove(file, fileList) {
this.fileList = fileList
},
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 < this.size
if (!isJPG) {
this.$message.error('上传图片只能是 JPG/PNG 格式!')
return false
}
if (!isLt2M) {
this.$message.error(`上传图片大小不能超过 ${this.size} MB!`)
return false
}
return true
},
openDialog() {
this.dialogVisible = true
},
closeDialog() {
this.dialogVisible = false
}
},
mounted() {
this.fileList = this.defaultList
}
}
</script>
<style>
.el-upload__tip {
font-size: 12px;
}
</style>
如何使用
<template>
<div>
<el-button @click="openImageSelector">选择图片</el-button>
<image-selector :actionUrl="uploadUrl" :defaultList="imageList" @confirm="handleImageSelect"></image-selector>
</div>
</template>
<script>
import ImageSelector from './ImageSelector'
export default {
components: {
ImageSelector
},
data() {
return {
uploadUrl: 'http://localhost:8080/upload',
imageList: []
}
},
methods: {
openImageSelector() {
this.$refs.imageSelector.openDialog()
},
handleImageSelect(fileList) {
this.imageList = fileList
}
}
}
</script>
使用时需要传入上传图片的接口地址,以及其他相关配置信息。通过 openDialog() 方法打开弹窗,选择完图片后,点击弹窗中的“确定”按钮,会触发 confirm 事件,将选择的图片列表作为参数传递出去。