vue中单个页面设置多个上传组件

发布时间:2024年01月24日

简述:

? ? ? ? 在最近的项目中,遇到单页面有多个上传图片的地方,如果每一个上传组件都写一个上传事件,在编码过程中又繁琐,后期维护也麻烦,最终在element-ui中找到了解决方法,在此记录一下。

html代码

<el-form-item?label="背景图:">
?????<el-upload
?????????class="avatar-uploader"
?????????action=""
?????????:show-file-list="false"
?????????list-type="picture"
?????????:http-request="Upload"
?????????:data="{name:'background_ImgUrl'}"
?????????:on-error="handleFailure"
?????????:before-upload="beforeAvatarUpload"
??????>
?????????<div?class="imgorigin"?v-if="!form.background_ImgUrl">
?????????????<i?class="el-icon-plus?first"></i>
?????????????<span?class="second">?上传?</span>
?????????</div>
?????????<img
?????????????v-if="form.background_ImgUrl"
?????????????:src="form.background_ImgUrl"
?????????????alt
?????????????class="img?avatar-uploader-icon"
??????????/>

?????</el-upload>
?????<span?class="logo">建议尺寸:1920*400</span>
</el-form-item>
<el-form-item?label="头像:">
?????<el-upload
?????????class="avatar-uploader"
?????????action=""
?????????:show-file-list="false"
?????????list-type="picture"
?????????:http-request="Upload"
?????????:data="{name:'avator_ImgUrl'}"
?????????:on-error="handleFailure"
?????????:before-upload="beforeAvatarUpload"
??????>
?????????<div?class="imgorigin"?v-if="!form.background_ImgUrl">
?????????????<i?class="el-icon-plus?first"></i>
?????????????<span?class="second">?上传?</span>
?????????</div>
?????????<img
?????????????v-if="form.background_ImgUrl"
?????????????:src="form.background_ImgUrl"
?????????????alt
?????????????class="img?avatar-uploader-icon"
??????????/>

?????</el-upload>
?????<span?class="logo">建议尺寸:1920*400</span>
</el-form-item>

图片上传,调用上传接口

注意:此处的file.data接收的参数,便是上面上传组件中定义的信息;通过拿到file.data中的数据,来判断是哪个上传弹框上传的数据,最后再根据业务需求,赋值给不同的变量

/**logo图片上传成功?*/
??Upload(file)?{
????console.log(file)
????var?fileName?=?file.file.name;
????var?formname?=?file.data.name;
????console.log('forname',formname)
    // 此处直接上传到阿里云
????上传接口.upload(file.file,fileName,?(res)?=>?{
??????if?(res.res.statusCode?==?"200")?{
??????????switch(formname){
????????????case?'background_ImgUrl'?:
??????????????this.form.background_ImgUrl?=?返回的图片路径
??????????????break
????????????case?'avator_ImgUrl1':
??????????????this.form.avatorValue_ImgUrl?=?返回的图片路径
??????????????break
??????????}
????????this.$message({
??????????message:?"上传成功!",
??????????type:?"success",
????????});
??????}?else?{
????????this.$message.warning("上传图片失败!");
??????}
????});
??}

文章来源:https://blog.csdn.net/weixin_46054156/article/details/135593090
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。