正文
vue2.0+Element UI 实现动态表单(点击按钮增删一排输入框)
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
对于动态增减表单项,Element UI 官方文档表单那一节已经介绍得很清楚了,我之前没有看见,绕了很多弯路,这里针对点击按钮增删一排输入框的问题做一个总结。
效果图如下
存在一排必填的姓名与手机号,点击增加后会新增一行,点击每行后面的删除图标则会删除该行
必填项很简单,就是普通表单:
<el-form
ref="form"
:rules="formRules"
:inline="true"
:model="form"
label-width="80px"
>
<!-- 固定项目 -->
<el-form-item label="姓名" prop="name">
<el-input v-model="form.name" palceholder="请输入姓名">
</el-input>
</el-form-item>
<el-form-item label="手机号" prop="phone">
<el-input v-model="form.phone" palceholder="请输入手机号">
</el-input>
</el-form-item>
</el-form>
<el-button @click="addItem" type="primary">增加</el-button>
export default {
name: 'dynamicForm',
data () {
return {
form: {
name: '',
phone: ''
},
formRules: {
name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
phone: [
{required: true, message: '请输入手机号', trigger: 'blur'},
{ pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码' }
]
}
}
}
}
动态表单部分:
<!-- 动态增加项目 -->
<!-- 不止一个项目,用div包裹起来 -->
<div v-for="(item, index) in form.dynamicItem" :key="index">
<el-form-item
label="姓名"
:prop="'dynamicItem.' + index + '.name'"
:rules="{
required: true, message: '姓名不能为空', trigger: 'blur'
}"
>
<el-input v-model="item.name"></el-input>
</el-form-item>
<el-form-item
label="手机号"
:prop="'dynamicItem.' + index + '.phone'"
:rules="[
{required: true, message: '手机号不能为空', trigger: 'blur'},
{ pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码' }
]"
>
<el-input v-model="item.phone"></el-input>
</el-form-item>
<el-form-item>
<i class="el-icon-delete" @click="deleteItem(item, index)"></i>
</el-form-item>
</div>
在data 的 form 里增加 dynamicItem
form: {
name: '',
phone: '',
dynamicItem: []
}
在methods里增加方法
methods: {
addItem () {
this.form.dynamicItem.push({
name: '',
phone: ''
})
},
deleteItem (item, index) {
this.form.dynamicItem.splice(index, 1)
}
}
每次点击增加按钮,会在dynamicItem里增加新的项,反映到页面上就是新增了一排输入框;而点击删除的时候,则通过index找到当前行删掉。