实现功能:
1.只能上传图片。2.只能上传一张图片。
这是效果图。
<el-upload
ref="my-upload"
class="avatar-uploader"
:action="action"
:limit="1"
:before-upload="fileChange"
:on-exceed="overstep"
:on-success="handleAvatarSuccess"
>
<img v-if="query.cover" :src="query.cover" class="avatar" />
//这个img实现上传成功,图片就会显示出来
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
//这个是上传文件成功出现的文件名
</el-upload>
action:必选参数,上传的地址
limit:最大允许上传个数
before-upload:上传文件之前会触发的事件。
fileChange(file) {
const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
const isJPG = typeArr.indexOf(file.type) !== -1;
if (!isJPG) {
this.$message.error("只能是图片!");
return isJPG;
}
},
on-exceed:数量超出限制触发的事件
overstep() {
this.$message.error("只能上传一张图片!");
},
on-success: 文件上传成功触发的事件。
handleAvatarSuccess(res, file) {
if (res.code == 1) {
this.query.cover = this.$host +'/public'+ res.data.img_url;
//把上传成功的图片路径取出来
}
},
最后加一个
清除已上传文件列表:clearFiles
this.$refs["my-upload"].clearFiles();
//这个是获取el-upload,然后实现清空