antdvue3 Form和modal一起使用 resetFields无效
时间: 2024-05-11 22:15:25 浏览: 253
快速解决Vue、element-ui的resetFields()方法重置表单无效的问题
在antdvue3中,要使resetFields生效,需要在modal关闭时调用resetFields方法。具体的代码实现如下:
```
<template>
<div>
<a-button @click="openModal">打开modal</a-button>
<a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
<a-form ref="form" :model="form">
<a-form-item label="姓名" :rules="{ required: true, message: '请输入姓名' }">
<a-input v-model:value="form.name" />
</a-form-item>
<a-form-item label="年龄" :rules="{ required: true, message: '请输入年龄' }">
<a-input-number v-model:value="form.age" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script>
import { ref } from 'vue';
import { Button, Modal, Form, Input, InputNumber } from 'ant-design-vue';
export default {
components: {
'a-button': Button,
'a-modal': Modal,
'a-form': Form,
'a-form-item': Form.Item,
'a-input': Input,
'a-input-number': InputNumber,
},
setup() {
const visible = ref(false);
const form = ref({ name: '', age: null });
const openModal = () => {
visible.value = true;
};
const handleOk = () => {
// 提交表单
form.value = { name: '', age: null };
visible.value = false;
};
const handleCancel = () => {
// 关闭modal时调用resetFields方法
const formRef = this.$refs.form;
formRef.resetFields();
form.value = { name: '', age: null };
visible.value = false;
};
return {
visible,
form,
openModal,
handleOk,
handleCancel,
};
},
};
</script>
```
在handleCancel方法中,我们首先获取form的ref,然后调用resetFields方法重置表单数据,最后将form的值设置为空对象{},将visible的值设置为false,关闭modal。这样就能够使resetFields生效了。
阅读全文