需求背景
在有些需求背景下,我们需要动态增加多字段列,满足现有数据格式,并且可以对数据列进行删除,形成数组对象集合。请参考下图!
废话不多说,上干货 code ,自行补充自己所需的逻辑及拓展
<template>
<Form ref="formDynamic" :model="formDynamic" :label-width="80" >
<div v-for="(item, index) in formDynamic.items" :key="index">
<Row>
<Col span="6">
<FormItem label="字段名:" :prop="'items.' + index + '.value'">
<Input type="text" v-model="item.value" ></Input>
</FormItem>
</Col>
<Col span="6">
<FormItem label="查询类型:" :prop="'items.' + index + '.value'">
<Input type="text" v-model="item.value" ></Input>
</FormItem>
</Col>
<Col span="6">
<FormItem label="类型值:" :prop="'items.' + index + '.value'">
<Input type="text" v-model="item.value" ></Input>
</FormItem>
</Col>
<Col span="6" >
<Button style="margin-left:10px" @click="handleRemove(index)" v-if="index>0">删除</Button>
</Col>
</Row>
</div>
<FormItem>
<Row>
<Col span="4">
<Button type="dashed" long @click="handleAdd" icon="md-add">添加</Button>
</Col>
</Row>
</FormItem>
<FormItem>
<Button type="primary" @click="handleSubmit('formDynamic')">查询</Button>
<Button @click="handleReset('formDynamic')" style="margin-left: 8px">重置</Button>
</FormItem>
</Form>
</template>
<script>
export default {
data () {
return {
index: 1,
formDynamic: {
items: [
{
value: '',
index: 1
}
]
}
}
},
methods: {
handleSubmit (name) {
console.log(this.formDynamic, '提交的数据')
this.$refs[name].validate((valid) => {
if (valid) {
this.$Message.success('Success!')
} else {
this.$Message.error('Fail!')
}
})
},
handleReset (name) {
this.$refs[name].resetFields()
},
handleAdd () {
if (this.formDynamic.items.length > 2) {
this.$Message.info('添加上限')
} else {
this.index++
this.formDynamic.items.push({
value: '',
index: this.index
})
}
},
handleRemove (index) {
if (index !== -1) {
this.formDynamic.items.splice(index, 1)
}
}
}
}
</script>