Skip to content

How to set form default values?

Set default values directly through the value field

This method is the simplest and most straightforward. You only need to assign a value to the value field in the form rules.

vue
<template>
   <form-create :rule="formRule" />
</template>
<script setup>
import { ref } from 'vue';
const formRule = ref([
  {
    type: 'input',
    field: 'username',
    title: 'Username',
    value: 'Default Username' // Set default value
  },
  {
    type: 'input',
    field: 'email',
    title: 'Email',
    value: 'example@example.com' // Set default value
  }
]);
</script>

Bind form data object through v-model

Use v-model to bind a data object and set default values in the object. This way, you can not only set initial values but also update form data at any time.

vue
<template>
   <form-create :rule="formRule" v-model="formData" />
</template>
<script setup>
import { ref } from 'vue';
const formData = ref({
  username: 'Default Username',
  email: 'example@example.com'
});
const formRule = ref([
  {
    type: 'input',
    field: 'username',
    title: 'Username',
  },
  {
    type: 'input',
    field: 'email',
    title: 'Email',
  }
]);
</script>

Dynamically set default values after form loads

Sometimes you need to dynamically set default values based on certain logic after the form loads. In this case, you can use the formApi.setValue method.

js
<template>
   <form-create :rule="formRule" v-model:api="formApi" />
</template>
<script setup>
import { ref, onMounted } from 'vue';


const formApi = ref(null);


const formRule = ref([
  {
    type: 'input',
    field: 'username',
    title: 'Username'
  },
  {
    type: 'input',
    field: 'email',
    title: 'Email'
  }
]);


onMounted(() => {
  // Dynamically set default values
  formApi.value.setValue('username', 'Dynamic Default Username');
  formApi.value.setValue('email', 'dynamic@example.com');
});
</script>

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.