Try to use setValues update the initialValues, but when I first time submit, it's the old value. Start from second time submit, it is the new value.Why and how to fix it?
<template>
<form @submit="onSubmit">
<input name="email" v-model="email" />
<!-- <span>{{ errors.email }}</span> -->
<input name="password" v-model="password" type="password" />
<!-- <span>{{ errors.password }}</span> -->
<button type="submit">submit</button>
</form>
</template>
<script setup>
import { useForm } from 'vee-validate';
import { computed, reactive, ref, inject, onMounted } from 'vue';
const { errors, setErrors, setFieldValue, handleSubmit } = useForm({
initialValues: {
email: 'example@gmail.com',
password: 'p@$$w0rd',
}
});
const onSubmit = handleSubmit(async (values, actions) => {
actions.setValues({
email: '12134123',
password: '1122200',
});
console.log(values);
});
</script>
Your code have 2 issues here.
First, the v-model
email and password don't link with the form. You can change it by
const {
...,
values
useFieldModel,
} = useForm({
initialValues: {
email: 'example@gmail.com',
password: 'p@$$w0rd',
},
});
const email = useFieldModel('email');
const password = useFieldModel('password');
...
Second, the values
that you use in onSubmit
is basically the form values when the submit button is clicked. In your code, the v-model
is not connected to the form, so even if you type anything in the input fields, it won't update the values with those changes. The values only receives the initial values specified in initialValues
, which in this case is 'example@gmail.com' and 'p@$$w0rd'.
After that, when you call actions.setValues
inside onSubmit
, you are setting new values for the form. So when you click the submit button again, the values will contain the newly set values
useForm
has expose a values
object, you can use it to get latest values of the form. I have update my demo here