Basic Usage

Let's start with a simple login form:

Schema

vue-formily need a form schema to work with, so let's define one:

import { defineSchema } from '@vue-formily';
import { required, email } from "@vue-formily/rules";

const loginForm = defineSchema({
  formId: "login",
  fields: [
    {
      formId: "email",
      type: "string",
      format: "{raw}",
      value: "",
      rules: [
        {
          ...required,
          message: "Please enter email address."
        },
        {
          ...email,
          message: "Please enter valid email address."
        }
      ],
      props: {
        label: "email",
        inputType: "email"
      }
    },
    {
      formId: "password",
      type: "string",
      rules: [
        {
          ...required,
          message: "Please enter password."
        }
      ],
      value: "",
      props: {
        label: "password",
        inputType: "password"
      }
    }
  ]
})

We're using required and email rules to validate fields. To learn more about validation rules, please check the document here.

Create New Form

Then we call $formily.addform to create new form element and injects it to Vue instance's forms object.

<template>
  <form class="login">
    <div v-for="(field, i) in forms.login.fields" :key="i" class="field">
      <label :for="field.formId">{{ field.label }}</label>
      <input v-model="field.raw" :type="field.props.inputType" :name="field.name" :id="field.formId" />
    </div>
  </form>
</template>

<script>
//  Vue 2.x
export default {
  created() {
    // Create new form element and injects it to `forms` object.
    this.$formily.addForm(loginForm);
  }
}

// Vue 3.x
import { useFormily } from '@vue-formily';

export default {
  setup() {
    const formily = useFormily();
    // Create newå form element and injects it to `forms` object.
    formily.add(loginForm);
  }
}
</script>

Live Demo

Edit this page on GitHub Updated at Fri, Feb 4, 2022