需求中经常会遇到 表单新增栏目的情况
一般是填写一个或者一组信息,并且会进行输入的验证
列举一个iviwe组件库的 只填写一个信息的验证方法
form 是整个表单的数据
data(){
return {
form: {
hostList: ['']
}
}
}
我们这里是地址栏的验证 随便列举的验证方法
首先我们看到循环 是循环form 的 hostList 数组
<template v-for="(item, index) in form.hostList">
prop字段 这里和验证至关重要
:prop="'hostList.' + index"
props 的值要要和数组名称保持一致 为hostList
后面加上.index ,index代表的是当前循环到的位数,所以props得到的 就是某个具体的指引
<FormItem
:key="index"
:label="'地址栏1' + (index + 1)"
:prop="'hostList.' + index"
class="callback-list"
:rules="{
required: true,
pattern: new RegExp(
/^$|(((localhost)|((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)|\w+[^\s]+(\.[^\s]+)+)(,((localhost)|((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)|\w+[^\s]+(\.[^\s]+)+))*)/,
'g'
),
message: '请填写正确的地址',
trigger: 'blur'
}"
>
<template v-for="(item, index) in form.hostList">
<FormItem
:key="index"
:label="'地址栏1' + (index + 1)"
:prop="'hostList.' + index"
class="callback-list"
:rules="{
required: true,
pattern: new RegExp(
/^$|(((localhost)|((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)|\w+[^\s]+(\.[^\s]+)+)(,((localhost)|((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)|\w+[^\s]+(\.[^\s]+)+))*)/,
'g'
),
message: '请填写正确的地址',
trigger: 'blur'
}"
>
<Row>
<Input
v-model="form.hostList[index]"
type="text"
placeholder="请输入地址"
@on-change="handleChange()"
></Input>
</Col>
<Button :disabled="index === 0" @click="handleRemove(index)">
删除
</Button>
<Button
v-if="
index === form.hostList.length - 1 ||
form.hostList.length === 1
"
@click="handleAdd"
>
新增
</Button>
</Row>
</FormItem>
</template>
点击删除的时候 删除一条数据
点击新增的时候 向数组新增空白数据
handleRemove(index) {
this.form.hostList.splice(index, 1)
},
handleAdd() {
this.form.hostList.push('')
},
iview组件库 动态新增表单信息 是类似的 只是经过了一点改造
https://www.iviewui.com/components/form