最近在項目中遇到了上傳文件是必填項的用法
剛開始按照傳統模式的必填項的做法,在el-form標簽中使用prop="fileUpdate"
然后再
結果在選擇好文件上傳,點擊提交表單后,該提示一直存在
於是想到了使用res的屬性去更改驗證的規則,動態將必填項移除
就有了
<el-form-item
ref="uploadElement" prop="fileUpdate" label="上傳文件">
<el-upload
class="upload-demo"
action="123"
:http-request="uploadSectionFile"
:before-remove="beforeRemove"
:limit="1"
:on-exceed="handleExceed"
:file-list="fileList"
>
<el-button size="small" :disabled="isDisabled" type="primary">點擊上傳</el-button>
</el-upload>
</el-form-item>
在提交表單的時候動態移除
this.publishRules.fileUpdate = []
this.$refs.uploadElement.clearValidate() // 如果上傳文件,就把必填校驗動態移除
這樣就可以驗證文件上傳是必填項了
后來遇到了一個問題,因為我的表單是放到dialog中,提交第一次成功后,模態框關閉,此時再次打開模態框,該驗證失效了
解決方法:在模態框關閉事件中,重新對publishRules.fileUpdate賦值就行了
this.publishRules.fileUpdate = [{ required: true, trigger: 'blur', message: '請選擇文件上傳' }] // 再將信息恢復成默認狀態
