ant组件radio换切导致表单校验失效

场景:
通过单选radio配合v-if来换切form-model-item,会可能触发rules的校验条件失效,如数据要求是必填项但没有值校验依然通过

解决方法:
每个form-model-item都绑定一个唯一的key值即可

// 通过radio来切换
<a-radio-group v-model="type" >
  <a-radio :value="1"> 文字1 </a-radio>
  <a-radio :value="2"> 文字2 </a-radio>
</a-radio-group>
<a-form-model :model="data" :rules="rules">
  // 添加唯一key
  <a-form-model-item v-if="type == 1" label="文字内容1" prop="content1" :key="1">
  <a-textarea v-model="data.content1" />
  </a-form-model-item>
  // 添加唯一key
  <a-form-model-item v-if="type == 2" label="文字内容2" prop="content2" :key="2">
  <a-textarea v-model="data.content2" />
  </a-form-model-item>
 </a-form-model>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是在Vue 3中使用Ant Design Vue进行表单校验的示例: ```vue <template> <a-modal v-model:visible="modalVisible" title="表单校验示例"> <a-form :form="form" @submit="handleSubmit"> <a-form-item label="用户名" name="username" :rules="[{ required: true, message: '请输入用户名' }]"> <a-input v-model:value="form.username" /> </a-form-item> <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码' }]"> <a-input-password v-model:value="form.password" /> </a-form-item> <a-form-item> <a-button type="primary" html-type="submit">提交</a-button> </a-form-item> </a-form> </a-modal> </template> <script> import { ref } from 'vue'; import { AModal, AForm, AFormItem, AInput, AInputPassword, AButton } from 'ant-design-vue'; export default { components: { AModal, AForm, AFormItem, AInput, AInputPassword, AButton, }, setup() { const form = ref(null); const modalVisible = ref(false); const handleSubmit = () => { form.value.validateFields((errors, values) => { if (!errors) { // 表单校验通过,执行提交逻辑 console.log(values); modalVisible.value = false; } }); }; return { form, modalVisible, handleSubmit, }; }, }; </script> ``` 在上述示例中,我们使用了Ant Design Vue的`AForm`、`AFormItem`、`AInput`、`AInputPassword`和`AButton`组件来构建表单。通过在`AFormItem`组件上设置`rules`属性,我们可以定义表单项的校验规则。在提交表单时,我们使用`validateFields`方法来进行表单校验,如果校验通过,则执行提交逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值