目录
1.说明
①在 formData
中定义个数组变量用来接受同一个字段的多个结果。
dynamicFormData: {
email: '',
// domains 字段下会有多个结果
domains: []
}
②使用 uni-forms-item
的 rules
属性定义单个表单域的校验规则。
<uni-forms-item :label="item.label+' '+index" required
:rules="[{'required': true,errorMessage: '域名项必填'}]" :key="item.id">
...
</uni-forms-item>
③name
需要动态指定,动态表单推荐使用 Array 类型,内容从左到右为绑定值的调用链。['domains',index,'value']
等同于 dynamicFormData.domains[index].value
<uni-forms-item
required
:label="item.label+' '+index"
:name="['domains',index,'value']"
:rules="[{'required': true,errorMessage: '域名项必填'}]"
:key="item.id"
>
...
</uni-forms-item>
④需要绑定值的组件的 v-model 也需要动态指定 dynamicFormData.domains[index].value
<uni-forms-item
required
:label="item.label+' '+index"
:name="['domains',index,'value']"
:rules="[{'required': true,errorMessage: '域名项必填'}]"
:key="item.id"
>
<uni-easyinput v-model="dynamicFormData.domains[index].value" placeholder="请输入域名" />
</uni-forms-item>
2.示例
html层:
<div v-for="(item,index) in formData.parts">
<uni-forms-item class="is-direction-top" :label="index == 0?'参与人':''" :required="index == 0"
:rules="[{'required': true,errorMessage: '请输入参与人'}]" :key="item.id" :name="['parts',index,'value']">
<template v-slot:label v-if="index > 0">
<div></div>
</template>
<view class="dmc">
<uni-easyinput v-model="formData.parts[index].value" placeholder="请输入参与人" />
<uni-icons class="dmc-btn" v-if="!index" @click="addParts" size="30" type="plus"
color="#666"></uni-icons>
<uni-icons class="dmc-btn" v-if="index" @click="delParts(index)" size="30" type="minus"
color="#e43d33"></uni-icons>
</view>
</uni-forms-item>
</div>
<div v-for="(item,index) in formData.workTime">
<uni-forms-item class="is-direction-top" :label="index == 0?'工作时间':''" :required="index == 0"
:rules="[{'required': true,errorMessage: '请输入工作时间'}]" :key="item.id"
:name="['workTime',index,'value']">
<template v-slot:label v-if="index > 0">
<div></div>
</template>
<view class="dmc">
<uni-datetime-picker type="datetimerange" v-model="formData.workTime[index].value" hide-second :clear-icon="false"
placeholder="请输入工作时间" />
<uni-icons class="dmc-btn" v-if="!index" @click="addWorkTime" size="30" type="plus"
color="#666"></uni-icons>
<uni-icons class="dmc-btn" v-if="index" @click="delWorkTime(index)" size="30" type="minus"
color="#e43d33"></uni-icons>
</view>
</uni-forms-item>
</div>
js层:
const resetForm = () => {
return {
bsNo: stationInfo.bsNo,
bsName: stationInfo.deptNm,
fieldNo: '',
fieldNm: '',
cropKey: '',
cropValue: '',
mediNm: '',
mediAcreage: '',
saKey: '',
saValue: '',
mediPerMu: '',
dosageMediKey: '',
dosageMediValue: '',
mediTotalMu: '',
mediContent: '',
mediModeKey: '',
mediModeValue: '',
participants: '',
parts: [{ value: getUser().userName, id: Date.now() }],
workTime: [{ value: [moment.now(), moment.now()], id: Date.now() }],
timeList: [] as any,
tempCount: NaN,
mediType: 6
}
};
// 初始表单数据设置
let formData = ref(resetForm());
3.总结
当某个字段为动态时,要用数组来存放多个值;要注意校验规则的写法。
我使用的是包含id及value的对象结构用来存在动态表单的数据。