1. 基本介绍
我们可以根据需要自定义输入数据条数,通过新增按钮新增块供用户输入。
当点击新增按钮会添加一组输入框,点击右侧删除标识进行移除。
2. 完整代码
页面完成实现代码如下:
<template>
<div>
<a-row>
<a-button @click="add">新增</a-button>
<a-button @click="save">保存</a-button>
</a-row>
<a-form-model
ref="ruleform"
:model="form"
:label-col="labelCol"
:wrapper-col="wrapperCol"
>
<div
v-for="(item, index) in form.contact"
:key="index"
:style="marginBottom: '15px'; marginLeft: '50px'"
>
<a-row>
<a-form-model-item
label="姓名"
:prop="`contact.${index}.userName`"
:label-col="labelCol"
:wrapper-col="wrapperCol"
>
<a-input
v-model="item.userName"
placeholder="请输入姓名"
:rules: [{ required: true, message: '姓名不能为空' }]
/>
</a-form-model-item>
<a-form-model-item
label="联系电话"
:prop="`contact.${index}.telephone`"
:label-col="labelCol"
:wrapper-col="wrapperCol"
>
<a-input
v-model="item.telephone"
:rules: [{ required: true, message: '电话不能为空' }]
placeholder="请输入电话"
/>
</a-form-model-item>
<a-icon
class="dynamic-delete-button"
type="minus-circle-o"
@click="() => remove(item)"
/>
</a-row>
</div>
</a-form-model>
</div>
</template>
<script>
export default {
name: 'index',
data () {
return {
form: {
contact: []
}
labelCol: { span: 4 },
wrapperCol: { span: 14 }
}
},
methods: {
save () {
this.$refs.ruleform.validate(valid => {
if (valid) {
console.log(this.form)
}
})
},
add () {
this.form.contact.push({
uuid: this.guid(),
userName: '',
telephone: ''
})
},
remove (item) {
this.form.contact = this.form.contact.filter(op => (op.uuid !== item.uuid))
},
guid () {
// 给每条新增数据生成唯一的uuid
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0
var v = c === 'x' ? r : (r & 0x3 | 0x8)
return v.toString(16)
})
}
}
}
</script>