场景
在日常开发中会遇到大量的表单提交,如果都使用单个数据的添加会很麻烦,所以大多数会选择使用动态添加的做法。
实现方式
点击 “添加” 按钮时,添加一个新的表单;
点击 “删除” 按钮时,通过拿到的当前下标再配合splice方法实现删除当前表单。
上代码
<template>
<template>
<div>
<a-row>
<a-col :span="8" :offset="8">
<div class="col"> <a-col-24>测试动作列表</a-col-24></div>
<!-- 循环data中定义的数组 -->
<div v-for="(item, index) in dataList" :key="index">
<!-- 表单内容 -->
<a-form label-width="80px" ref="form" :model="item">
<a-row>
<a-col :span="9">
<a-form-item :rules="usernameRule" label="姓名" name="username" :label-col="{ span: 8 }"
:wrapper-col="{ span: 16 }">
<a-select show-search allow-clear :options="selectData"
v-model:value="item.username"></a-select>
</a-form-item>
</a-col>
<a-col :span="11">
<a-form-item :rules="[{ required: true, message: '请输入年龄', trigger: 'blur' }]" label="年龄"
name="age" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
<a-input-number :min="0" :max='100' style="width:128px"
v-model:value="item.age"></a-input-number>
</a-form-item>
</a-col>
<a-col :span="3" :offset=1>
<a-button class='btn' @click="removeIdx(item, index)" type="text">删除</a-button>
</a-col>
</a-row>
</a-form>
</div>
<!-- 操作按钮 -->
<a-button class="btn" @click="addForm" type="success">添加</a-button>
<a-button @click="submit">提交</a-button>
</a-col>
<a-col :span="8"></a-col>
</a-row>
</div>
</template>
<script>
import { get, post } from '@/utils/http/Axios'
export default {
data() {
const usernameRule = [
{ required: true, message: '请选择姓名!', trigger: 'blur' },
{
validator: (rule, value, callback) => {
const arr = this.dataList.filter(item => item.username === value)
if (arr.length > 1) {
return Promise.reject()
}
return Promise.resolve()
},
message: '姓名重复!',
trigger: 'blur'
}
]
return {
usernameRule,
// 表单绑定数据
dataList: [
{
username: '',
age: ''
}
],
selectData: [
{ "value": "基尼太美" }, { "value": "练习两年半" }, { "value": "小黑子" }, { "value": "开庭" }, { "value": "鸡爪" }, { "value": "鸡脚" }, { "value": "吃鸡" }, { "value": "哈哈哈" }, { "value": "邓琪凡" }, { "value": "意大利" }, { "value": "坤柳" }, { "value": "坤蛋" }, { "value": "陈胜" }, { "value": "武广" }, { "value": "秦始皇" }, { "value": "刘备" }, { "value": "蔡文姬" }, { "value": "孙尚香" }, { "value": "无敌" }, { "value": "赵子龙" }
]
}
},
methods: {
// 添加操作
addForm() {
this.dataList.push({
username: '',
age: ''
})
},
// 删除操作
removeIdx(item, index) {
this.dataList.splice(index, 1)
},
// 提交
submit() {
console.log(this.dataList)
}
}
}
</script>
<style scoped>
.col {
position: relative;
font-size: 16px;
font-weight: 800;
margin-top: 10px;
margin-bottom: 10px;
}
.col:before {
position: absolute;
content: '';
background-color: #70b936;
width: 4px;
height: 16px;
position: absolute;
left: -10px;
top: 60%;
margin-top: -10px;
}
.btn {
color: #70b936;
}
</style>
效果
查看数据
可以看到提交了三个表单数据。
补充
提交时需要校验重复或者必填的话如果按正常方式写
this.$refs['form'].validate()
会报错
因为此时的表单是通过for循环生成的表单,在这种情况下获得表单的方法会得到一个数组而不是对象, 直接使用 validate 方法会报错。
我这里解决也是使用for循环进行校验。
for (let i = 0; i < this.dataList.length; i++) {
this.$refs['form'][i].validate().then(() => {
console.log(this.dataList);
})
}