uniapp的项目某个模块的需求是
- 有一个按钮点击添加表单,则会在原表单的基础上再添加一组,然后点击提交时会校验这些表单是否为空,下方为示例代码
<template>
<div>
<form>
<div v-for="(input, index) in inputs" :key="index">
<label>Input {{ index + 1 }}</label>
<u--input v-model="input.value"></u--input>
<u--input v-model="input.value1"></u--input>
<u--input v-model="input.value2"></u--input>
<u--input v-model="input.value3"></u--input>
</div>
</form>
<button @click="addInputs">Add Inputs</button>
<button @click="submitForm">提交校验</button>
</div>
</template>
<script>
export default {
data() {
return {
inputs: [{
value: '1',
value1: '2',
value2: '3',
value3: '4',
}]
}
},
methods: {
addInputs() {
// this.inputs.push(...this.inputs)
this.inputs.push({
value: '',
value1: '',
value2: '',
value3: '',
})
},
submitForm() {
this.inputs.forEach(item => {
const {
value,
value1,
value2,
value3
} = item
switch (true) {
case !value:
uni.showToast({
title: '请输入value',
icon: 'none'
})
break
case !value1:
uni.showToast({
title: '请输入value1',
icon: 'none'
})
break
case !value2:
uni.showToast({
title: '请输入value2',
icon: 'none'
})
break
case !value3:
uni.showToast({
title: '请输入value3',
icon: 'none'
})
break
default:
uni.showToast({
title: '提交成功',
icon: 'none'
})
break
}
})
}
}
}
</script>
- 这种循环并解构再判断的方式在这个demo中是没问题的,但是项目中的话就会出现若多组表单的话,它只会校验第一组的表单,其他的表单就算没填写,也会校验通过,下面的方法是换了一个js的api来实现的
clickFun(arr) {
let bool = arr.every(item => {
if (!item.pointAdd) {
uni.$u.toast('请输入点位地址');
return false
} else if (!item.policeOffice) {
uni.$u.toast('请输入所属派出所');
return false
} else if (!item.policeWay) {
uni.$u.toast('请输入民警联系方式');
return false
} else if (!item.propertyName) {
uni.$u.toast('请输入物业名称');
return false
} else if (!item.propertyWay) {
uni.$u.toast('请输入物业联系方式');
return false
} else if (!item.zoneId) {
uni.$u.toast('请选择防区');
return false
} else if (item.materialList.length === 0) {
uni.$u.toast('请上传现场实地照片');
return false
} else {
return true;
}
})
return bool
},
clickFun参数为传递的数组,也就是点击提交的时候去调用这个方法,然后把数组传过去就可以了。下方是调用校验方法的代码
//this.pointAddressList就是clickFun方法传递的数组。
if (this.clickFun(this.pointAddressList)) {
this.Investigation();//此处是调用的接口,不用管
}