uniapp基于uview的动态表单处理方式以及验证方法(验证涉及map循环需要等待执行)

页面样式:(存在新增动态表单)
uniapp基于uview的动态表单处理方式以及验证方法(验证涉及map循环需要等待执行)_第1张图片
代码:

// 主要体现在common-form组件的动态命名方法,formData指向本页的一个数组对象
<view class="" v-for="(item,index) in formData" :key="index">
			<view class="u-flex u-flex-between u-font-18 u-pl-16 u-pt-20 u-pr-16">
				<view>成员{{index+1}}</view>
				<view v-if="index>0" @click="deleteIt(index)">删除</view>
			</view>
			<common-form :ref="'myForm'+index" @click="onSubmit" :formData="formData[index]" :form="form[index]" :rules="rules[index]"/>
		</view>
		<view class="u-px-32">
			<u-button text="+ 新增" @click="addIt()" type="primary" :plain="true" class="u-mt-20 u-mb-90" ></u-button>
		</view>
// 数据初始化
data() {
			return {
				form:[
					{
						relationship:'2022-08-05',
						name:'1',
						company:'2321413341',
						vocation:'2321413341',
						phone:'2321413341'
					},
				],
				formData: [
					[
						{ label: '家庭关系', prop: 'relationship', type: 'input' },
						{ label: '姓名', prop: 'name', type: 'input' },
						{ label: '单位', prop: 'company', type: 'input' },
						{ label: '职业', prop: 'vocation', type: 'input' },
						{ label: '联系电话', prop: 'phone', type: 'input'},
					],
				],
				rules:[
					{
						relationship:{required:true,message:'请输入家庭关系',trigger:['blur', 'change']},
					},
				]
					
				
			}
		},

删除和新增

deleteIt(index){
				this.form.splice(index,1)
				this.formData.splice(index,1)
				this.rules.splice(index,1)
			},
			addIt(){
				let formObj = {
						relationship:'',
						name:'',
						company:'',
						vocation:'',
						phone:''
					}
				let formDataArr = [
						{ label: '家庭关系', prop: 'relationship', type: 'input' },
						{ label: '姓名', prop: 'name', type: 'input' },
						{ label: '单位', prop: 'company', type: 'input' },
						{ label: '职业', prop: 'vocation', type: 'input' },
						{ label: '联系电话', prop: 'phone', type: 'input'},
					]
				let rulesObj = {
						relationship:{required:true,message:'请输入家庭关系',trigger:['blur', 'change']},
					}
				this.form.push(formObj)
				this.formData.push(formDataArr)
				this.rules.push(rulesObj)
			},

验证方法,使用Promise.all方法

async onSubmit() {
				let subStatus = false // 定义一个开关来知道是否全部验证通过
				await Promise.all(
					this.formData.map(async (item,index)=>{
						await this.$refs[`myForm${index}`][0].validate().then(async res => {
						subStatus = res
						}).catch(errors => {
							subStatus = false
							uni.$u.toast('请填写相关信息')
						})
					})
				)
				
				if (subStatus) {
					uni.setStorageSync('XXXX', this.form) // 暂存本地
					uni.getStorageSync('XXXX') // 获取
					//做要做的事....
				}
			}

你可能感兴趣的:(uni-app,uni-app,uview,promise.all方法)