vue3 + antd + a-form 动态数组表单校验

2024-11-05  本文已影响0人  空空雨夜

业务场景

一个表单提交不同的类型用户,可以添加多个用户,页面如下:

image.png

最终的代码在最后,可以滑到最后

表单结构

需要提交表单的表单结构,分别有主播和员工的两个列表,如下:

interface PersonItem {
  username: string
  label: string
}

interface IForm {
  anchor: PersonItem[] // 主播列表
  staff: PersonItem[] // 员工列表
  [key: string]: any // 这里是为了阻止使用中括号取对象的值失TS报错
}
const form = reactive<IForm>({
  anchor: [{ username: '', label: '' }],
  staff: [{ username: '', label: '' }]
})

模板结构

<template>
  <a-form ref="formRef" :model="form">
    <div class="section">
      <h3>主播</h3>
      <div v-for="(item, index) in form.anchor" class="row">
        <a-form-item label="姓名" :name="`anchor-${index}-username`" :rules="rules.username">
          <a-input v-model:value="item.username"></a-input>
        </a-form-item>
        <a-form-item label="标签" :name="`anchor-${index}-label`" :rules="rules.label" style="margin-left: 20px;">
          <a-input v-model:value="item.label"></a-input>
        </a-form-item>
        <DeleteOutlined class="row-delete" @click="removePerson('anchor', index)" />
      </div>
      <a-button type="text" @click="addPerson('anchor')">+ 添加</a-button>
    </div>
    <div class="section">
      <h3>员工</h3>
      <div v-for="(item, index) in form.staff" class="row">
        <a-form-item label="姓名" :name="`staff-${index}-username`" :rules="rules.username">
          <a-input v-model:value="item.username"></a-input>
        </a-form-item>
        <a-form-item label="标签" :name="`staff-${index}-label`" :rules="rules.label" style="margin-left: 20px;">
          <a-input v-model:value="item.label"></a-input>
        </a-form-item>
        <DeleteOutlined class="row-delete" @click="removePerson('staff', index)" />
      </div>
      <a-button type="text" @click="addPerson('staff')">+ 添加</a-button>
    </div>
    <a-form-item>
      <a-button @click="onCancel">取消</a-button>
      <a-button type="primary" @click="onSubmit">提交</a-button>
    </a-form-item>
  </a-form>
</template>

自定义校验规则

在a-form自定义检验函数中,分别返回rule、value、callback。
rule:就是校验的配置规则,在这个对象中有个field属性,这个属性记录了模板中a-form-item中绑定的name值。
value: 对应表单属性的值。但是在数组表单中获取不到,所以我们需要通过rule的field获取对应的值。
callback:这个回调函数是必须调用的,否则校验自定义校验函数没有结果。如果不调用,也可以返回Promise。在本例中使用的返回Promise的方式。

通过rule的field属性,获取到对应的属性,取到值在进行校验判断。具体代码如下:

const inputValidator = (rule: Rule1) => {
  const [cellKey, index, prop] = rule.field.split('-')
  if ((form[cellKey][index][prop] ?? '') === '') {
    return Promise.reject(new Error(rule.message as unknown as string))
  } else {
    return Promise.resolve()
  }
}

最终代码

<script setup lang="ts">
import { DeleteOutlined } from '@ant-design/icons-vue';
import { FormInstance, message } from 'ant-design-vue';
import { Rule } from 'ant-design-vue/es/form';
import { reactive, ref } from 'vue';

interface PersonItem {
  username: string
  label: string
}

interface IForm {
  anchor: PersonItem[],
  staff: PersonItem[],
  [key: string]: any
}
const form = reactive<IForm>({
  anchor: [{ username: '', label: '' }],
  staff: [{ username: '', label: '' }]
})

type Rule1 = Rule & {
  field: string
}

const inputValidator = (rule: Rule1) => {
  const [cellKey, index, prop] = rule.field.split('-')
  if ((form[cellKey][index][prop] ?? '') === '') {
    return Promise.reject(new Error(rule.message as unknown as string))
  } else {
    return Promise.resolve()
  }
}


const rules = {
  username: [{ required: true, validator: inputValidator, message: '姓名不能为空' }],
  label: [{ required: true, validator: inputValidator, message: '标签不能为空' }]
}

const formRef = ref<FormInstance | null>(null)

const onSubmit = () => {
  formRef.value?.validate().then(() => {
    message.success('提交成功')
  }).catch(() => {
    console.log('表单校验失败')
  })
}

const onCancel = () => {
  formRef.value?.resetFields()
}

const addPerson = (type: string) => {
  const person: PersonItem = {username: '', label: ''}
  form[type].push(person)
}

const removePerson = (type: string, index:number) => {
  const personList = form[type]
  if (personList.length === 1) return
  personList.splice(index, 1)
}
</script>

<template>
  <a-form ref="formRef" :model="form">
    <div class="section">
      <h3>主播</h3>
      <div v-for="(item, index) in form.anchor" class="row">
        <a-form-item label="姓名" :name="`anchor-${index}-username`" :rules="rules.username">
          <a-input v-model:value="item.username"></a-input>
        </a-form-item>
        <a-form-item label="标签" :name="`anchor-${index}-label`" :rules="rules.label" style="margin-left: 20px;">
          <a-input v-model:value="item.label"></a-input>
        </a-form-item>
        <DeleteOutlined class="row-delete" @click="removePerson('anchor', index)" />
      </div>
      <a-button type="text" @click="addPerson('anchor')">+ 添加</a-button>
    </div>
    <div class="section">
      <h3>员工</h3>
      <div v-for="(item, index) in form.staff" class="row">
        <a-form-item label="姓名" :name="`staff-${index}-username`" :rules="rules.username">
          <a-input v-model:value="item.username"></a-input>
        </a-form-item>
        <a-form-item label="标签" :name="`staff-${index}-label`" :rules="rules.label" style="margin-left: 20px;">
          <a-input v-model:value="item.label"></a-input>
        </a-form-item>
        <DeleteOutlined class="row-delete" @click="removePerson('staff', index)" />
      </div>
      <a-button type="text" @click="addPerson('staff')">+ 添加</a-button>
    </div>
    <a-form-item>
      <a-button @click="onCancel">取消</a-button>
      <a-button type="primary" @click="onSubmit">提交</a-button>
    </a-form-item>
  </a-form>
</template>

<style lang="scss" scoped>
.row {
  display: flex;

  .row-delete {
    margin-top: 10px;
    margin-left: 10px;
  }
}
</style>

效果

image.png

总结

上一篇 下一篇

猜你喜欢

热点阅读