使用场景:table中有好几个select下拉框,比如当第一个下拉框的值选中为某一个时,后面的几个下拉框为必填,否则不必填
解决方案:首先在table的最外侧用form包裹,然后哪里需要验证,就在哪个元素外面用formItem包裹,原理很简单,可是由于我的数据包裹的比较多,数据还是从上一个页面传过来的,所以就整了好长时间,主要是prop绑定的这块有问题。
ps:如果你想当第一个选中那个需要的项时,后面几个立马就显示‘必填’字样,可以用iview中form API中的error属性,看下面例子就可以
<i-form ref="tailForm" :model="tailForm">
<i-table :columns="detailColumns" :data="tailForm.detailDatas">
<!-- 尾差处理方式 -->
<template slot-scope="{ row, index }" slot="penny">
<Select
transfer
v-model="tailForm.detailDatas[index].penny"
@on-change="pennyChange($event, index)"
>
<Option value="01">退回客户</Option>
<Option value="02">客户不要了</Option>
</Select>
</template>
<!-- 收款银行代码 -->
<template slot-scope="{ row, index }" slot="bankId">
<FormItem
:prop="'tailForm.detailDatas['+index+'].bankId'"
:rules="tailForm.detailDatas[index].penny === '01' ? { required: true, message: '必填' } : {}"
:error="tailForm.detailDatas[index].penny === '01' ? '必填' : ''"
>
<Select filterable transfer v-model="tailForm.detailDatas[index].bankId">
<Option value="01">招商</Option>
<Option value="02">农商</Option>
</Select>
</FormItem>
</template>
</i-table>
</i-form>
做完这一步后,有个问题是,加载页面和切换选项时会报错:please transfer a valid prop path to form item,
这是因为formItem的属性props的路径不需要加form绑定的model的名字,直接绑定model下面的路径即可,
我这个例子里面的我当时写的prop为:prop="‘tailForm.detailDatas[’+index+’].bankId’",我的form绑定的域为tailForm,所以改为:prop="‘detailDatas[’+index+’].bankId’",这样就不会在报错了,完整代码如下:
<i-form ref="tailForm" :model="tailForm">
<i-table :columns="detailColumns" :data="tailForm.detailDatas">
<!-- 尾差处理方式 -->
<template slot-scope="{ row, index }" slot="penny">
<Select
transfer
v-model="tailForm.detailDatas[index].penny"
@on-change="pennyChange($event, index)"
>
<Option value="01">退回客户</Option>
<Option value="02">客户不要了</Option>
</Select>
</template>
<!-- 收款银行代码 -->
<template slot-scope="{ row, index }" slot="bankId">
<FormItem
:prop="'detailDatas['+index+'].bankId'"
:rules="tailForm.detailDatas[index].penny === '01' ? { required: true, message: '必填' } : {}"
:error="tailForm.detailDatas[index].penny === '01' ? '必填' : ''"
>
<Select filterable transfer v-model="tailForm.detailDatas[index].bankId">
<Option value="01">招商</Option>
<Option value="02">农商</Option>
</Select>
</FormItem>
</template>
</i-table>
</i-form>