表单

提交表单

v-formly-v3 提交表单的三种方式。

  1. 使用默认的提交按钮,通过设置 button='default'
  2. 使用 slot 暴露出来的 submit function,通过设置 button='custom' 并传入 name='button' 的 slot。
  3. 使用 ref 获取 form 实例,直接调用实例的 validate function,eg: form.value.validate()

代码演示

<template>
  <div>
    <a-divider>button = 'default' 显示默认的提交按钮</a-divider>
    <v-formly-v3
      v-model="formData1"
      :meta="meta"
      :button="'default'"
      @form-submit="submit"
    />
    <a-divider>button = 'custom' 自定义提交按钮,传入 default slot</a-divider>
    <v-formly-v3
      v-model="formData2"
      :meta="meta"
      :button="'custom'"
      @form-submit="submit"
    >
      <template v-slot:button="{ loading, clearForm, submitForm }">
        <div class="btns">
          <a-button type="danger" @click="clearForm"> 自定义重置 </a-button>
          <a-button type="primary" @click="submitForm" :loading="loading">
            自定义提交
          </a-button>
        </div>
      </template>
    </v-formly-v3>
    <a-divider>button = undefined 不需要提交按钮,完全由外部控制</a-divider>
    <v-formly-v3 ref="form" v-model="formData3" :meta="meta" />
    <div class="btns">
      <a-button type="danger" @click="clear"> 重置 </a-button>
      <a-button type="primary" @click="submitAsync"> 提交 </a-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, toRaw, unref } from "vue";
import type VFormly from "@/ant-design-vue/AFormly.vue";

const form = ref<null | InstanceType<typeof VFormly>>(null);
const formData1 = ref({});
const formData2 = ref({});
const formData3 = ref({});
const meta = {
  properties: {
    name: {
      title: "姓名",
      type: "string",
      ui: {
        showRequired: true,
      },
    },
    asyncError: {
      title: "异步错误(2秒)",
      type: "string",
      ui: {
        showRequired: true,
        validatorAsync: (val: any) => {
          return new Promise((resolve) => {
            setTimeout(() => {
              resolve(
                !val
                  ? [
                      {
                        keyword: "required",
                        message: "Required asyncError",
                      },
                    ]
                  : []
              );
            }, 2000);
          });
        },
      },
    },
  },
  required: ["name", "asyncError"],
};

function submit(value: any) {
  console.log(value);
}
function clear() {
  formData3.value = {};
}
async function submitAsync() {
  const valid = await form.value!.validate();
  if (valid) {
    console.log(toRaw(unref(formData3)));
  }
}
</script>
复制

API

参数说明类型默认值
:layout表单布局'horizontal' | 'vertical' | 'inline''horizontal'
:button提交按钮'default' | 'custom'默认不显示提交按钮
:metaJSON Schema + UI Schema--
:value(v-model)表单绑定数据object-
button自定义提交按钮slot{ loading, clearForm, submitForm }
@form-reset重置数据后回调事件function(data)-
@form-submit数据验证成功或失败后回调事件function({ valid, data })-

组件方法

名称描述
validate校验表单
clearForm重置表单,触发 form-reset 事件
submitForm校验表单,在校验完成后触发 form-submit 事件