在项目中经常遇到动态表单的业务。在编辑动态表单时需要回显新增后的内容。本文介绍Ant Design of Vue 的动态表单回显。
比如新增时添加了两行动态表单,在第二次编辑时需要进行回显。
下面是表单的HTML代码
<a-row
:gutter='20'
v-for="(k, index) in form.getFieldValue('keys')"
:key="k"
v-bind="index === 0 ? formItemLayout : formItemLayoutWithOutLabel"
:label="index === 0 ? 'Passengers' : ''"
:required="false"
>
<a-col :span='1'>a-col>
<a-col :span="11">
<a-form-item v-bind="formItemLayout" label="参数名称">
<a-input
v-decorator="[
`param[${k}]`,
{
validateTrigger: ['change', 'blur'],
initialValue: account && account.param,
rules: [
{
required: true,
whitespace: true,
message: '请输入参数名称',
},
],
},
]"
/>
a-form-item>
a-col>
<a-col :span="11">
<a-form-item v-bind="formItemLayout" label="参数描述">
<a-input
v-decorator="[
`paramDescription[${k}]`,
{
validateTrigger: ['change', 'blur'],
initialValue: account && account.paramDescription,
rules: [
{
required: true,
whitespace: true,
message: '请输入参数描述',
},
],
},
]"
/>
a-form-item>
a-col>
<a-col :span='1'>
<a-icon
v-if="form.getFieldValue('keys').length > 1"
class="dynamic-delete-button"
type="minus-circle-o"
:disabled="form.getFieldValue('keys').length === 1"
@click="() => remove(k)"
/>
a-col>
a-row>
<a-row :gutter='20'>
<a-col :span="24">
<a-form-item v-bind="formItemLayoutWithOutLabel">
<a-button type="dashed" style="width: 90%" @click="add">
<a-icon type="plus" /> 添加参数
a-button>
a-form-item>
a-col>
a-row>
表单编辑的回显逻辑,通过setFieldsValue进行回显
beforeCreate () {
this.form = this.$form.createForm(this)
// this.form.getFieldDecorator('keys', { initialValue: [0], preserve: true })
},
watch: {
async visible (val) {
if (this.account) {
this.form.getFieldDecorator('keys', { initialValue: this.keys, preserve: true })
let params = {
indexOrder: 'ASC',
indexOrderKey: 'id',
currentPage: 0,
numberPerPage: 10
}
const res = await getAbilityParams(this.account.id, params)
if (res.success) {
let data = res.data.rows
let param = []
let paramDescription = []
this.keys = []
data.forEach((item, index) => {
this.keys.push(index)
param.push(item.param)
paramDescription.push(item.description)
})
this.form.setFieldsValue({
keys: this.keys
})
this.$nextTick(() => {
this.form.setFieldsValue({
param: param,
paramDescription: paramDescription
})
})
} else {
this.$message.error(res.desc)
}
} else {
this.form.getFieldDecorator('keys', { initialValue: [0], preserve: true })
}
}
},
添加一行和删除一行逻辑
remove (k) {
const { form } = this
const keys = form.getFieldValue('keys')
if (keys.length === 1) {
return
}
form.setFieldsValue({
keys: keys.filter(key => key !== k)
})
},
// 动态项增加
add () {
const { form } = this
const keys = form.getFieldValue('keys')
let length = keys.length
const nextKeys = keys.concat(keys[length - 1] + 1)
form.setFieldsValue({
keys: nextKeys
})
}
打开编辑模态框后。新增的数据会回显,同时可以进行删除和添加一行的操作,下面是打开编辑的模态框,参数名称和参数描述完成了回显。