vue + element-UI 实现图片嵌在表单里,图片和表单一起上传
element
A Vue.js 2.0 UI Toolkit for Web
项目地址:https://gitcode.com/gh_mirrors/eleme/element
免费下载资源
·
⭐️个人博客:caohongyuan.com,更多分享,欢迎浏览!⭐️
如下图,需求要实现点击一个按钮,可以让表单的内容和图片一起上传,只请求后台一次!
思路:
1.让图片formData放在表单formData中一起上传,实现不了,目前前台获取不到图片的本地地址;
2.让图片的 vm.$refs.upload.submit() 放在post上传表单的函数下上传,这样会请求后台两次,并速度也很慢;
3.那就让表单formData放在图片formData中,随着图片一起上传,这个实现了,具体代码如下:
<style>
input[type="file"] {
display: none;
}
.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>
<div class="upload-image">
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
<el-form-item label="活动名称" prop="name">
<el-input v-model="ruleForm.name" style="width: 300px"></el-input>
</el-form-item>
<el-form-item label="上传图片" ref="uploadElement" prop="imageUrl">
<el-input v-model="ruleForm.imageUrl" v-if="false"></el-input>
<el-upload
class="avatar-uploader"
ref="upload"
:show-file-list="false"
action="/index/upload"
:before-upload="beforeUpload"
:on-change="handleChange"
:auto-upload="false"
:data="ruleForm">
<img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</div>
<script>
var uploadImageVue = new Vue({
el: '.upload-image',
data: {
ruleForm: {
name: '',
imageUrl: '',
},
rules: {
name: [
{required: true, message: '请输入活动名称', trigger: 'blur'},
],
imageUrl: [
{required: true, message: '请上传图片', trigger: 'blur'},
],
}
},
methods: {
submitForm(formName) {
let vm = this;
this.$refs[formName].validate((valid) => {
if (valid) {
vm.$refs.upload.submit();
} else {
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
this.ruleForm.imageUrl = '';
},
handleChange (file, fileList) {
this.ruleForm.imageUrl = URL.createObjectURL(file.raw);
},
beforeUpload(file) {
return true;
},
}
})
</script>
中间实现了很多小技巧,比如:
1.预览图片;
2.利用input实现图片上传与否的验证。
3.样式等;
ps:更详细的讲解,欢迎浏览个人网站:曹鸿源个人站点 | www.caohongyuan.com | 一个爱生活的程序员
欢迎指导,有啥问题下面留言。
千而的大狮子~
GitHub 加速计划 / eleme / element
54.06 K
14.63 K
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:3 个月前 )
c345bb45
7 个月前
a07f3a59
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update table.md
* Update transition.md
* Update popover.md 7 个月前
更多推荐
已为社区贡献4条内容
所有评论(0)