uview下表单动态校验的问题

一、前言

最近开发网格小程序,其中涉及到动态添加家属,对表单进行动态校验问题,但uview没办法实现,后面参照其他博客和自己的理解,终于解决了此问题。

动态表单效果图

二、解决方案

1、动态使用,v-for需要放在u-form下的view下面

在这里插入图片描述

2、rules和表单model下面放置一个同名数组

在这里插入图片描述

3、修改uview中的源码

在 validateField 方法中修改如下
源码:

// 属性链数组
const propertyChain = child.prop.split(".");
const propertyName =
	propertyChain[propertyChain.length - 1];

const rule = this.formRules[child.prop];
// 如果不存在对应的规则,直接返回,否则校验器会报错
if (!rule) return;
// rule规则可为数组形式,也可为对象形式,此处拼接成为数组
const rules = [].concat(rule);

修改后:

// 属性链数组
const propertyChain = child.prop.split(".");
const propertyName =
	propertyChain[propertyChain.length - 1];
//修改:将const改为let 
let rule = this.formRules[child.prop];
//修改:链式是无法通过上面的方式获取的,改为下面的方式
if(!rule){
	rule=uni.$u.getProperty(
	this.formRules,
	child.prop
	);

}
// 如果不存在对应的规则,直接返回,否则校验器会报错
if (!rule) return;

4、动态添加数据

//添加家属
addRelation() {
	if(!this.houseInformation.isChange) return;
	if(this.houseInformation.userList.length && !this.houseInformation.userList?.[this.houseInformation.userList.length-1]?.relation){
		uni.$showMsg('请先选择上一个的户主关系')
		return
	}
	
	let relation = {
		identityNumber:'',
	  userName: '',
	  userBirthday: '',
	  userSex: '',
	  relation: '',
	  userTel: '',
	  personnelId:''
	}
	this.houseInformation.userList.push(relation);
	this.rules.userList.push(this.relationRules);
	this.$refs.houseInformation.setRules(this.rules)

},

在这里一定要注意:添加的relation 一定要用变量申明,而不要放在data里面,否则会出现引用地址一致,导致表单与表单之间的校验混乱情况。

三、总结

前端基础一定要打牢,有机会还是看一些源码提升自己!!!

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值