在ElementPlus中,可以使用beforeUpload
属性来指定上传文件之前的钩子函数,在该函数中可以对文件进行判断并进行相关操作。
首先,在data中定义一个isImage
变量来记录文件是否为图片,初始值为false。然后,在钩子函数中判断文件的类型是否为图片类型。
<template>
<el-upload
class="upload-demo"
action="/your-upload-api"
:before-upload="handleBeforeUpload"
>
<el-button size="small" type="primary">Click to Upload</el-button>
</el-upload>
</template>
<script>
export default {
data() {
return {
isImage: false
}
},
methods: {
handleBeforeUpload(file) {
const fileType = file.type
if (fileType.startsWith('image/')) {
this.isImage = true
} else {
this.isImage = false
this.$message.error('Please upload images only.')
return false // 阻止文件上传
}
}
}
}
</script>
在handleBeforeUpload
函数中,首先获取文件的类型,然后使用startsWith
方法判断是否以image/
开头,如果是,则将isImage
设置为true,否则将其设置为false,并且返回false来阻止文件上传。同时,可以根据情况给出相应的错误提示。