误区
ant for vue 的 Modal 自带确认和关闭按钮,如果在 modal 里面加上 slot=“footer” 的底部按钮会覆盖原本 modal 自带的按钮,使 form 的校验不生效!!!
注意
<a-form :form="form"> 的 form 属性不能少
实现代码
<!-- 對話框 -->
<a-modal
:visible.sync="visible" //是否显示对话框
:title="textMap[modalType]"
ok-text="确认"
:cancel-text="$t('cancel')" //按钮国际化
@ok="handleSubmit" // 对话框提交按钮
@cancel="visible = false" //对话框的取消按钮
:closable="false" //不显示对话框的x按钮
>
<a-form :model="tempData" v-bind="layout" :form="form">
<a-form-item label="名称">
<a-input name="name" v-decorator="['name', rules.name]" />
</a-form-item>
<a-form-item label="详情">
<a-input type="textarea" name="description" v-decorator="['description', rules.description]" />
</a-form-item>
</a-form>
</a-modal>
export default {
name: 'user',
components: {},
data () {
return {
tempData: {
name: '',
description: ''
},
modalType: '',
form: this.$form.createForm(this),
textMap: {
add: this.$t('create'),
update: this.$t('update')
},
layout: {
labelCol: { span: 6 },
wrapperCol: { span: 15 }
},
rules: {
name: {
rules: [
{ required: true, message: '请输入姓名', trigger: 'blur' },
{ min: 2, max: 15, message: '姓名为2-15个字符', trigger: 'blur' }
]
},
description: {
rules: [
{ required: true, message: '请输入详情', trigger: 'blur' },
{ min: 2, max: 50, message: '详情为2-50个字符', trigger: 'blur' }
]
}
},
methods: {
createData () {},
updateData () {},
handleSubmit (e) {
e.preventDefault()
this.form.validateFields((err, values) => {
if (!err) {
console.log('values', values)
this.tempData.name = values.name
this.tempData.Description = values.description
if(this.modalType === 'create') {
this.createData()
} else {
this.updateData()
}
}
})
}
}
}
}
}
这时可能有一个需求是编辑功能,当我们直接给表单赋值时用 value 或 v-modal 会报下面的错误
Warning: `getFieldDecorator` will override `value`, so please don‘t set `value` directly...
这时我们需要换种方式给表单赋值,用 form 的 api setFieldsValue 方法,代码实现如下
handleUpdate (row) {
this.$nextTick(() => {
this.form.setFieldsValue({
name: this.tempData.name,
description: this.tempData.description
})
})
}
注意
还有一种情况,如果 handleUpdate 方法需要使用异步的时候 async ,上面的 setFieldsValue 方法需要放在所有加 await 方法的后面