在項(xiàng)目中回官,經(jīng)常遇到表單有上傳圖片甘畅、文件的情況,但是這些不經(jīng)過v-model控制芽腾。所以對(duì)于表單校驗(yàn)就不能直接通過element自帶的校驗(yàn)處理旦装。這里就有個(gè)問題,我又要校驗(yàn)其他表單內(nèi)容摊滔,又要特殊處理不是表單元素的內(nèi)容校驗(yàn)阴绢。嘗試過
clearValidate
但是處理起來還是有點(diǎn)問題。后來發(fā)現(xiàn)Form-Item
一個(gè)屬性error
,可以在你需要校驗(yàn)的時(shí)候添加校驗(yàn)提示艰躺,不需要的時(shí)候清空呻袭,就可以滿足我的業(yè)務(wù)需求
例:校驗(yàn)上傳圖片為必填項(xiàng)
image.png
<el-form ref="ruleForm" size="mini" :rules="rules" :model="form" label-width="170px">
<!-- ....一些表單元素 -->
<el-form-item ref="ruleImg" label="車型圖片:" required :error="carImgError">
<el-upload
ref="imgUpload"
:action="uploadUrl"
accept="image/*"
list-type="picture"
:before-upload="handleBefore"
:on-remove="handleRemove"
:on-success="handleSuccess"
:file-list="fileList"
>
<el-button icon="iconfont icon-upload">圖片上傳</el-button>
<span slot="tip" class="el-upload__tip ml">請(qǐng)上傳jpg/png格式的圖片</span>
</el-upload>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
uploadUrl: window.global_config.uploadURL,
carImgError: '', // 關(guān)鍵 表單內(nèi)上傳組件校驗(yàn)提示
rules: {
// 一些表單校驗(yàn)
},
fileList: [{ name: '默認(rèn)車型圖片', url: 'https://upload-images.jianshu.io/upload_images/18912919-2dd7184b2309af4f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240'}],
form: {}
},
methods: {
getForm() {
this.form.address = this.fileList[0] && this.fileList[0].url || ''
if (!this.form.address) this.carImgError = '請(qǐng)上傳車型圖片' // 關(guān)鍵
this.$refs.ruleForm.validate().then(() => {
if (this.form.address) {
// 表單上傳接口
} else {
return false
}
})
},
// 圖片移除
handleRemove(file, fileList) {
this.fileList = []
},
handleBefore(file) {
const isJPG = (file.type === 'image/png' || file.type === 'image/jpeg')
if (!isJPG) {
this.$message.error('請(qǐng)上傳jpg/png格式的圖片')
}
return isJPG
},
// 圖片上傳成功
handleSuccess(response, file, fileList) {
this.$message.success('圖片上傳成功')
// 關(guān)鍵 清空提示
this.carImgError = ''
//此處我只上傳一張圖片 再次上傳更換原來的圖片
this.fileList = [{ name: file.name, url: response.data }]
}
}
}
</script>
總結(jié):1、 在表單提交時(shí)腺兴,同時(shí)進(jìn)行表單校驗(yàn)(rules內(nèi)定義的校驗(yàn))左电、上傳組件是否有文件(判斷是否有圖片地址)。表單校驗(yàn)成功后校驗(yàn)值是否存在含长,如果存在進(jìn)行提交券腔,不存在不做處理伏穆。(表單校驗(yàn)和上傳組件需要同時(shí)校驗(yàn)拘泞,防止只提示一個(gè)校驗(yàn)錯(cuò)誤信息,所以在表單校驗(yàn)成功后還需判斷圖片值是否存在枕扫,或者判斷
carImgError
是否為空)
2陪腌、在圖片上傳成功后,需要清空校驗(yàn)錯(cuò)誤信息烟瞧,(最好在圖片移除的時(shí)候加上錯(cuò)誤信息this.carImgError = '請(qǐng)上傳車型圖片'
,但是我懶)
結(jié)束