vue+elementUI实现表单和图片上传及验证功能示例
本文实例讲述了vue+elementui实现表单和图片上传及验证功能。分享给大家供大家参考,具体如下:
最终实现需求如下图:
form表单内容与重点人员图片同时上传且图片为必填项
分析弹框页需要解决的问题有:
1、表单内容的验证及必填项
2、新增和编辑用同一个组件如何处理数据
3、图片需要和信息一起传递(即不允许自动上传)
4、图片必填的验证问题
针对上述问题作出方案:
1、el-form的表单验证需要注意几个地方:
a:el-form-item的prop值需要和表单标签的v-model值保持一致
例如:
<el-form-item label="姓名:" prop="name"> <el-input style="width:1rem;" v-model="addkeypersonform.name" placeholder="请输入姓名"></el-input> </el-form-item>
b:验证规则有直接用element官网提供的也有自定义的
例如:其中checknumber就是自定义的验证数字的正则
rules: { // 表单验证 name: [ { required: true, message: '必填项', trigger: 'blur' } ], age: [ { required: true, message: '必填项', trigger: 'blur' }, { validator: checknumber, trigger: 'blur' } ], sex: [ { required: true, message: '必填项', trigger: ['blur', 'change'] } ], nationlity: [ { required: true, message: '必填项', trigger: ['blur', 'change'] } ], usertype: [ { required: true, message: '必填项', trigger: ['blur', 'change'] } ], idcard: [ { required: true, message: '必填项', trigger: 'blur' }, { validator: checkidcard, trigger: 'blur' } ], registered: [ { required: true, type: 'array', message: '必填项', trigger: ['blur', 'change'] } ], registereddetails: [ { required: true, message: '必填项', trigger: 'blur' } ], domicile: [ { required: true, type: 'array', message: '必填项', trigger: ['blur', 'change'] } ], domiciledetails: [ { required: true, message: '必填项', trigger: 'blur' } ], file: [ { required: true, message: '请上传图片' } ], platenumber: [ { validator: checkplatenum, trigger: 'change' } ] }
2、新增和编辑问题需要我们在打开组件的时候传递两个值
props: { dialogtype: { //是新增还是编辑,用于判断 type: string }, keypersonlist: { //表单的原始值 type: object } }
3、图片和form表单内容一起上传
首先我们需要阻止图片的自动上传让它等到我们点击保存按钮的时候再一起传给后台
我们看这段代码就是图片上传组件
<el-upload class="upload-img" :style="{backgroundimage:'url(' + dialogimageurl + ')', backgroundrepeat:'no-repeat', backgroundposition:'center center', backgroundsize: 'contain'}" ref="uploadxls" action="aaa" ::limit="1" :show-file-list="false" :on-change="handlepicturecardpreview" :before-upload="beforeupload" accept="image/png,image/gif,image/jpg,image/jpeg"> <i v-show="!dialogimageurl" class="el-icon-upload avatar-uploader-icon"></i> <div v-show="!dialogimageurl" slot="tip" class="el-upload__text upload__tip">上传照片</div> </el-upload>
action我们随便填一个就好,重点是这一句:before-upload="beforeupload"在图片上传之前执行beforeupload方法在里面return false就可以实现阻止upload自动上传
// 阻止upload的自己上传,进行再操作 beforeupload (file) { this.formdata.append('file', file) return false }
关于图片和表单文件一起上传我们选择了formdata格式存储数据用于上传
选择了图片并填写必填信息之后点击保存进行上传操作,在onsubmit方法里把表单信息都append到formdata里that.$refs.uploadxls.submit() // 提交时触发了before-upload函数--》完成图片的上传即执行beforeupload方法
4、图片必填的验证问题:
a、如果没有选择图片点击保存则图片提示:请上传图片
b、此时选择了图片则“请上传图片”消失
验证规则里有一条file就是做图片必填验证的
file: [ { required: true, message: '请上传图片' } ]
c、在编辑重点人员信息时重点人员图片已存在没有进行图片上传操作此时点击保存应该不提示“请上传图片”,未解决这个问题我们在上传时添加判断:
如果是编辑信息且未进行过图片上传操作则去掉file验证
就是以下代码
that.rules.file = [{ required: true, message: '请上传图片' }] if (that.dialogtype !== 'add' && !this.doupload) { that.rules.file = [] that.$refs['uploadelement'].clearvalidate() }
整个弹框组件的代码如下:
<template> <div class="add-keyperson-dialog"> <el-form :inline="true" ref="addkeypersonform" :model="addkeypersonform" class="demo-form-inline" label-width="1.4rem" :rules="rules"> <el-form-item label="姓名:" prop="name"> <el-input style="width:1rem;" v-model="addkeypersonform.name" placeholder="请输入姓名"></el-input> </el-form-item> <el-form-item label="性别:" label-width="0.64rem" prop="sex"> <el-select style="width:0.65rem;" v-model="addkeypersonform.sex" placeholder="请选择"> <el-option label="男" value="1"></el-option> <el-option label="女" value="2"></el-option> </el-select> </el-form-item> <el-form-item label="年龄:" label-width="0.64rem" prop="age"> <el-input style="width:0.65rem;" v-model="addkeypersonform.age" placeholder="请输入"></el-input> </el-form-item> <el-form-item prop="file" class="upload-img-form" ref="uploadelement"> <el-upload class="upload-img" :style="{backgroundimage:'url(' + dialogimageurl + ')', backgroundrepeat:'no-repeat', backgroundposition:'center center', backgroundsize: 'contain'}" ref="uploadxls" action="aaa" ::limit="1" :show-file-list="false" :on-change="handlepicturecardpreview" :before-upload="beforeupload" accept="image/png,image/gif,image/jpg,image/jpeg"> <i v-show="!dialogimageurl" class="el-icon-upload avatar-uploader-icon"></i> <div v-show="!dialogimageurl" slot="tip" class="el-upload__text upload__tip">上传照片</div> </el-upload> </el-form-item> <!--<img :src="dialogimageurl"/>--> <el-form-item label="身份证号:" prop="idcard"> <el-input style="width:1.7rem;" v-model="addkeypersonform.idcard" placeholder="请输入身份证号"></el-input> </el-form-item> <el-form-item label="国籍:" label-width="0.64rem" prop="nationlity"> <el-select style="width:1.37rem;" v-model="addkeypersonform.nationlity" placeholder="请选择"> <el-option label="中国" value="中国"></el-option> </el-select> </el-form-item> <el-form-item label="车牌号:" prop="platenumber"> <el-input style="width:1.7rem;" v-model="addkeypersonform.platenumber" placeholder="请输入车牌号"></el-input> </el-form-item> <el-form-item label="类别:" label-width="0.64rem" prop="usertype"> <!--<el-select style="width:1.37rem;" v-model="addkeypersonform.usertype" placeholder="请选择"> <el-option label="精神病人" value="0"></el-option> <el-option label="涉毒" value="1"></el-option> </el-select>--> <el-select style="width:1.37rem;" v-model="addkeypersonform.usertype" placeholder="请选择"> <el-option v-for="item in keypersontype" :key="item.id" :label="item.datavalue" :value="item.datakey"> {{item.datavalue}} </el-option> </el-select> </el-form-item> <el-form-item label="户籍地:" prop="registered"> <!-- <el-select style="width:1.3rem;" v-model="addkeypersonform.huji" placeholder="请选择"> <el-option label="青岛市" value="0"></el-option> <el-option label="北京市" value="1"></el-option> </el-select>--> <el-cascader style="width:1.3rem;" :options="options" placeholder="请选择" v-model="addkeypersonform.registered" :rules="{type: 'array'}" @change="handlechange" :separator="' '"> </el-cascader> </el-form-item> <el-form-item prop="registereddetails"> <el-input style="width:3.55rem;" v-model="addkeypersonform.registereddetails" placeholder="请输入详细地址"></el-input> </el-form-item> <el-form-item label="居住地:" prop="domicile"> <!--<el-select style="width:1.3rem;" v-model="addkeypersonform.juzhu" placeholder="请选择"> <el-option label="青岛市" value="0"></el-option> <el-option label="北京市" value="1"></el-option> </el-select>--> <el-cascader style="width:1.3rem;" :options="options" placeholder="请选择" :rules="{type: 'array'}" v-model="addkeypersonform.domicile" @change="handlechange" :separator="' '"> </el-cascader> </el-form-item> <el-form-item prop="domiciledetails"> <el-input style="width:3.55rem;" v-model="addkeypersonform.domiciledetails" placeholder="请输入详细地址"></el-input> </el-form-item> <el-form-item label="经纬度:"> <el-input style="width:5rem;" v-model="position" placeholder="请选择经纬度" @click.native="showposition=true"></el-input> </el-form-item> <!--<el-form-item label="所属人员库:"> <el-select style="width:4.75rem;" v-model="addkeypersonform.library" placeholder="请选择"> <el-option label="全国重点人员库1" value="0"></el-option> <el-option label="全国重点人员库2" value="1"></el-option> </el-select> </el-form-item>--> <el-form-item label="问题及现实表现:" prop="problem"> <el-input style="width:5rem;" v-model="addkeypersonform.problem" placeholder="请输入问题及现实表现"></el-input> </el-form-item> <el-form-item label="采取措施:" prop="measure"> <el-input style="width:5rem;" v-model="addkeypersonform.measure" placeholder="请输入措施"></el-input> </el-form-item> <el-form-item label="控制人员:" prop="controller"> <el-table :data="addkeypersonform.controller" stripe height="1rem" style="width: 5rem;"> <el-table-column prop="name" label="姓名" show-overflow-tooltip> </el-table-column> <el-table-column prop="sex" label="性别" width="60"> </el-table-column> <el-table-column prop="birth" show-overflow-tooltip label="出生日期"> </el-table-column> <el-table-column prop="post" show-overflow-tooltip label="职务"> </el-table-column> <el-table-column prop="phone" show-overflow-tooltip label="联系电话"> </el-table-column> <el-table-column label="操作" width="60"> <template slot-scope="scope"> <el-button @click.native.prevent="deleterow(scope.$index)" type="text" size="small"> 移除 </el-button> </template> </el-table-column> </el-table> <el-button type="text" icon="el-icon-plus" @click="innervisible = true">继续添加</el-button> </el-form-item> <el-form-item label="备注:" prop="remark"> <el-input style="width:5rem;" type="textarea" rows="1" v-model="addkeypersonform.remark" placeholder="请输入备注"></el-input> </el-form-item> <el-form-item label="最后更新时间:" v-if="addkeypersonform.updatetime"> <p style="width:4.7rem;">{{addkeypersonform.updatetime}}</p> </el-form-item> <el-form-item style="text-align:center;display:block;"> <el-button type="primary" @click="onsubmit" :disabled="dosubmitflag">保存</el-button> </el-form-item> </el-form> <!--添加控制人员弹框------------------开始--> <el-dialog width="4.2rem" title="添加控制人员" v-if="innervisible" :visible.sync="innervisible" append-to-body :before-close="closefun"> <personnel-control-add @add-person="addperson" ref="addform"></personnel-control-add> </el-dialog> <!--添加控制人员弹框------------------结束--> <!--选择经纬度弹框------------------开始--> <el-dialog width="5.1rem" title="选择经纬度" v-if="showposition" :visible.sync="showposition" append-to-body :before-close="closeposition"> <personnel-add-position ref="addposition" @add-position="addposition" :position-form1="positionform"></personnel-add-position> </el-dialog> <!--选择经纬度弹框------------------结束--> </div> </template>
<script> import options from '../../../static/js/country-data.js' import personnelcontroladd from './personnelcontroladd.vue' import axiosmap from './../../api/map' import axioscontrol from './../../api/control' import personneladdposition from './personneladdposition.vue' export default { components: { personneladdposition, personnelcontroladd}, name: 'add-keyperson-dialog', props: { dialogtype: { type: string }, keypersonlist: { type: object } }, computed: { position: { // 经纬度 // getter get: function () { let str = '' if (this.addkeypersonform.longitude !== '' && this.addkeypersonform.latitude !== '' && this.addkeypersonform.longitude !== null && this.addkeypersonform.latitude !== null) { str = this.addkeypersonform.longitude + ',' + this.addkeypersonform.latitude } return str }, // setter set: function (newvalue) { } } }, /* watch: { keypersonlist: { // 深度监听,可监听到对象、数组的变化 handler (newquestion, oldquestion) { this.addkeypersonform = object.assign({}, this.keypersonlist) this.dialogimageurl = object.assign({}, this.keypersonlist).iconurl }, deep: true } }, */ data () { var checknumber = (rule, value, callback) => { let regen = /^[1-9]\d*$/ if (!regen.test(value)) { callback(new error('正整数')) } else { callback() } } var checkidcard = (rule, value, callback) => { let regen = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|x|x)$)/ if (!regen.test(value)) { callback(new error('请输入正确身份证')) } else { // 校验位按照iso 7064:1983.mod 11-2的规定生成,x可以认为是数字10 // 下面分别分析出生日期和校验位 let num = value.touppercase() let len, re len = num.length if (len === 15) { re = new regexp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/) let arrsplit = num.match(re) // 检查生日日期是否正确 let dtmbirth = new date('19' + arrsplit[2] + '/' + arrsplit[3] + '/' + arrsplit[4]) let bgoodday bgoodday = (dtmbirth.getyear() === number(arrsplit[2])) && ((dtmbirth.getmonth() + 1) === number(arrsplit[3])) && (dtmbirth.getdate() === number(arrsplit[4])) if (!bgoodday) { callback(new error('请输入正确身份证')) } else { // 将15位身份证转成18位 //校验位按照iso 7064:1983.mod 11-2的规定生成,x可以认为是数字10 let arrint = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] let arrch = ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'] var ntemp = 0, i num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6) for (i = 0; i < 17; i++) { ntemp += num.substr(i, 1) * arrint[i] } num += arrch[ntemp % 11] callback() } } if (len === 18) { re = new regexp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|x)$/) let arrsplit = num.match(re) // 检查生日日期是否正确 let dtmbirth = new date(arrsplit[2] + '/' + arrsplit[3] + '/' + arrsplit[4]) let bgoodday bgoodday = (dtmbirth.getfullyear() === number(arrsplit[2])) && ((dtmbirth.getmonth() + 1) === number(arrsplit[3])) && (dtmbirth.getdate() === number(arrsplit[4])) if (!bgoodday) { callback(new error('请输入正确身份证')) } else { // 检验18位身份证的校验码是否正确。 //校验位按照iso 7064:1983.mod 11-2的规定生成,x可以认为是数字10 let valnum let arrint = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] let arrch = ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'] var ntemp = 0, i for (i = 0; i < 17; i++) { ntemp += num.substr(i, 1) * arrint[i] } valnum = arrch[ntemp % 11] if (!isnan(num.substr(17, 1))) { callback() } if (valnum !== num.substr(17, 1)) { callback(new error('请输入正确身份证')) } } } } } var checkplatenum = (rule, value, callback) => { if (value && value !== '') { let regen = /(^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领a-z]{1}[a-z]{1}[a-z0-9]{4}[a-z0-9挂学警港澳]{1}$)/ if (!regen.test(value)) { callback(new error('请输入正确车牌号')) } else { callback() } } else { callback() } } return { dosubmitflag: false, showposition: false, doupload: false, keypersontype: [], // 重点人员类型列表 addkeypersonform: object.assign({}, this.keypersonlist), positionform: { longtitude: this.keypersonlist.longitude, latitude: this.keypersonlist.latitude }, options: options, // 存放城市数据, innervisible: false, // 继续添加弹框 dialogimageurl: object.assign({}, this.keypersonlist).iconurl, // 图片 formdata: new formdata(), rules: { // 表单验证 name: [ { required: true, message: '必填项', trigger: 'blur' } ], age: [ { required: true, message: '必填项', trigger: 'blur' }, { validator: checknumber, trigger: 'blur' } ], sex: [ { required: true, message: '必填项', trigger: ['blur', 'change'] } ], nationlity: [ { required: true, message: '必填项', trigger: ['blur', 'change'] } ], usertype: [ { required: true, message: '必填项', trigger: ['blur', 'change'] } ], idcard: [ { required: true, message: '必填项', trigger: 'blur' }, { validator: checkidcard, trigger: 'blur' } ], registered: [ { required: true, type: 'array', message: '必填项', trigger: ['blur', 'change'] } ], registereddetails: [ { required: true, message: '必填项', trigger: 'blur' } ], domicile: [ { required: true, type: 'array', message: '必填项', trigger: ['blur', 'change'] } ], domiciledetails: [ { required: true, message: '必填项', trigger: 'blur' } ], file: [ { required: true, message: '请上传图片' } ], platenumber: [ { validator: checkplatenum, trigger: 'change' } ] } } }, created () { this.getkeypersontype() }, methods: { handlechange (value) { }, // 获取重点人员类型 getkeypersontype: function () { let that = this let param = { typecodes: 'usertype' } axiosmap.getkeypersontype(param) .then(res => { if (res.data.code === 200) { that.keypersontype = res.data.rows['0'].usertype that.keypersontype.foreach(function (item) { if (that.addkeypersonform.usertype === item.datavalue) { that.addkeypersonform.usertype = item.datakey } }) // that.keypersontype.unshift({datavalue: '全部', datakey: ''}) } else { that.$message.error({ message: res.data.message }) } }) }, // 添加控制人员 addperson (person) { this.addkeypersonform.controller.push(person) }, // 添加经纬度 addposition (position) { this.addkeypersonform.longitude = position[0] this.addkeypersonform.latitude = position[1] this.showposition = false }, // 删除某个控制人员 deleterow (index) { this.addkeypersonform.controller.splice(this.addkeypersonform.controller[index], 1) }, // 关闭新增控制人员 closefun () { this.$refs.addform.$refs.controlform.resetfields() this.innervisible = false }, // 关闭经纬度 closeposition () { // this.$refs.addposition.$refs.addposition.resetfields() this.showposition = false }, // 图片预览 handlepicturecardpreview (file) { this.dialogimageurl = file.url this.addkeypersonform.file = file.url this.doupload = true this.$refs['addkeypersonform'].validatefield('file') }, // 阻止upload的自己上传,进行再操作 beforeupload (file) { this.formdata.append('file', file) return false }, // 上传重点人员信息 onsubmit: function () { let that = this that.formdata = new formdata() that.rules.file = [{ required: true, message: '请上传图片' }] if (that.dialogtype !== 'add' && !this.doupload) { that.rules.file = [] that.$refs['uploadelement'].clearvalidate() } that.$refs['addkeypersonform'].validate((valid) => { if (valid) { that.formdata.append('name', that.addkeypersonform.name) if (that.addkeypersonform.sex === '男') { that.addkeypersonform.sex = 1 } else if (that.addkeypersonform.sex === '女') { that.addkeypersonform.sex = 2 } that.formdata.append('sex', that.addkeypersonform.sex) that.formdata.append('age', that.addkeypersonform.age) that.formdata.append('idcard', that.addkeypersonform.idcard) that.formdata.append('nationlity', that.addkeypersonform.nationlity) that.formdata.append('platenumber', that.addkeypersonform.platenumber) that.formdata.append('usertype', that.addkeypersonform.usertype) that.formdata.append('longitude', that.addkeypersonform.longitude) that.formdata.append('latitude', that.addkeypersonform.latitude) that.formdata.append('registered', that.addkeypersonform.registered.join('-')) that.formdata.append('registereddetails', that.addkeypersonform.registereddetails) that.formdata.append('domicile', that.addkeypersonform.domicile.join('-')) that.formdata.append('domiciledetails', that.addkeypersonform.domiciledetails) that.formdata.append('problem', that.addkeypersonform.problem) that.formdata.append('measure', that.addkeypersonform.measure) that.formdata.append('controller', json.stringify(that.addkeypersonform.controller)) that.formdata.append('remark', that.addkeypersonform.remark) if (that.dialogtype === 'add') { that.$refs.uploadxls.submit() // 提交时触发了before-upload函数 that.dosubmitflag = true axioscontrol.savenewkeyperson(that.formdata) .then(res => { that.dosubmitflag = false if (res.data.code === 200) { that.$message({ type: 'success', message: '添加成功' }) that.$refs.addkeypersonform.dialogimageurl = 'none' that.$refs.uploadxls.clearfiles() that.$refs.addkeypersonform.resetfields() that.filename = '' that.uploadform = new formdata() that.$emit('savepersonsuccess') } else { that.$message.error({ message: res.data.message }) } }) /* .catch(err => { that.$message.error({ message: err }) }) */ } else { if (!that.doupload) { that.formdata.append('iconurl', that.addkeypersonform.iconurl) } // 还要传id that.formdata.append('id', that.addkeypersonform.id) that.dosubmitflag = true axioscontrol.saveeditkeyperson(that.formdata) .then(res => { that.dosubmitflag = false if (res.data.code === 200) { that.$message({ type: 'success', message: '添加成功' }) that.$refs.addkeypersonform.dialogimageurl = 'none' that.$refs.uploadxls.clearfiles() that.$refs.addkeypersonform.resetfields() that.filename = '' that.uploadform = new formdata() that.$emit('savepersonsuccess') } else { that.$message.error({ message: res.data.message }) } }) } } else { this.$message({ type: 'warning', message: '请填写正确格式' }) return false } }) } } } </script>
<style scoped> .add-keyperson-dialog{ position:relative; height:7.2rem; overflow:auto; } .add-keyperson-dialog .demo-form-inline{ font-size:0.13rem; color:#666; } /*上传图片样式*/ .add-keyperson-dialog .upload-img-form{ width: 1rem; height: 1.35rem; position: absolute; right:0.2rem; top:0rem; border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; text-align: center; } .add-keyperson-dialog .upload-img{ width: 1rem; height: 1.35rem; overflow:hidden; } .add-keyperson-dialog .upload-img:hover { border-color: #409eff; color: #409eff; } .add-keyperson-dialog .avatar-uploader-icon { position:relative; z-index:100; font-size: 0.3rem; color: #8c939d; width: 0.9rem; height: 1.35rem; line-height: 1rem; text-align: center; } .add-keyperson-dialog .upload-img:hover .avatar-uploader-icon { color: #409eff } .add-keyperson-dialog .avatar { width: 100%; height: auto; display: block; } .add-keyperson-dialog .upload__tip { font-size: 0.13rem; text-align: center; position: relative; z-index:10; top: -0.7rem; } </style>
希望本文所述对大家vue.js程序设计有所帮助。