今天遇到了iview動態(tài)添加表單,并且深度驗證表單的問題搅幅。
功能如圖:
科目可以動態(tài)新增阅束,并且科目非空,成績在0-100區(qū)間內茄唐。
- html部分息裸,v-for遍歷form子屬性scoreList。
- 內部FormItem prop規(guī)則為[子屬性].[索引].[子屬性]
- rules手動指定
...
<Table border :columns="column" :data="form.scoreList">
<template slot-scope="{ row, index }" slot="subject">
<FormItem :prop="`scoreList.${index}.subject`" :label-width="0" :rules="rules.subject">
<Select v-model="form.scoreList[index].subject" transfer>
<Option v-for="(item,idx) in subjectList" :key="index + '_' + idx" :value="item.value"
:disabled="hasSelectedSubject[item.value]">
{{item.label}}
</Option>
</Select>
</FormItem>
</template>
<template slot-scope="{ row, index }" slot="score">
<FormItem :prop="`scoreList.${index}.score`" :label-width="0" :rules="rules.score">
<Input v-model="form.scoreList[index].score" />
</FormItem>
</template>
<template slot-scope="{ row, index }" slot="edit">
<Button type="error" size="small" @click="delSubject(index)">刪除</Button>
</template>
</Table>
...
data () {
return {
// 表單數(shù)據(jù)
form: {
name: '',
sex: 'male',
provinceCode: '',
cityCode: '',
scoreList: [{
subject: '',
score: ''
}]
},
rules: {
...
subject: [
{ required: true, message: '請選擇科目沪编!', trigger: 'change' }
],
score: [
{ required: true, message: '請輸入成績呼盆!', trigger: 'blur' },
{ pattern: /^\d+$/, message: '成績必須為整數(shù)!', trigger: 'blur' },
{
validator (rule, value, callback) {
value = Number(value)
if (value <= 100 && value >= 0) {
callback()
} else {
callback(new Error('成績必須為0-100之間的整數(shù)!'))
}
},
message: '請輸入成績蚁廓!', trigger: 'blur'
}
]
},
...
}
}