uniapp 下 动态表单的校验问题
刚捣鼓Uniapp不久,做一个动态表单的Demo,发现不能动态校验,因为对前段知识研究不深,瞎弄。
目前问题解决了,解决的思路如下:
在uni的组件【uni-form】的验证方法【validateField】增加代码,下面圈红圈的是新增的代码。
同时,业务的界面的数据和校验规则定义也要有要求,下面是完整的业务界面的Demo代码:
//包裹预报 <template> <view> <u--form labelPosition="left" :model="form" :rules="rules" ref="form1"> <!-- <u-form-item label="运单号:" labelWidth="90px"> <u--input v-model="form.waybill"></u--input> </u-form-item> --> <view v-for=" (good,index) in form.goodsAry" :key="index"> <view class="p_item"> <view class="goodName"> <u-form-item :prop="`goodsAry.${index}.name`" borderBottom> <u--input v-model="good.name" placeholder="名称"></u--input> </u-form-item> </view> <view class="goodInfo"> <u-form-item :prop="`goodsAry.${index}.qty`" borderBottom> <u--input v-model="good.qty" placeholder="数量" ></u--input> </u-form-item> <u-form-item borderBottom :prop="`goodsAry.${index}.price`"> <u--input v-model="good.price" placeholder="单价" ></u--input> </u-form-item> <u-form-item borderBottom :prop="`goodsAry.${index}.amount`"> <u--input v-model="good.amount" placeholder="总价" ></u--input> </u-form-item> </view> <view class="opt"> <u-button @click="addGood()">add</u-button> </view> </view> </view> </u--form> <u-button @click="submit()">提交</u-button> </view> </template> <script> const itemRule= { name: [{ type: 'string', required: true, message: '请输入用户名', trigger: ['blur', 'change'], }, { min: 6, message: '请输入至少6个字符', trigger: ['blur', 'change'], } ], qty: [{ type: 'string', required: true, message: '请填写数量', trigger: ['blur', 'change'], } ], price:[{ type: 'string', required: true, message: '请填写单价', trigger: ['blur', 'change'], }] }; export default { data() { return { rules: { goodsAry: [] }, form: { waybill: '', goodsAry: [], qty: 0, amount: 0.00 }, } }, onReady: function() { // this.$refs.form.setRules(this.rules.goodsRule); this.addGood(); }, methods: { addGood() { this.form.goodsAry.push({}); this.rules.goodsAry.push(itemRule); } , submit() { this.$refs.form1.validateField('goodsAry.0.name') this.$refs.form1.validate().then(res => { uni.$u.toast('校验通过') }).catch(errors => { uni.$u.toast('校验失败') }) } } } </script> <style lang="scss"> .p_item {} .p_item .goodName {} .p_item .goodInfo { display: flex; flex-direction: row; } .p_item .opt {} </style>