I have implemented a composable that includes a function for handling errors and a template for displaying the errors:
useErrorHandling.js
import { ref } from 'vue';
export default function useErrorHandling() {
const errors = ref(null);
function errorFor(field) {
return errors.value && errors.value[field]
? errors.value[field]
: null;
}
return {
errors,
errorFor,
};
}
ValidationErrors.vue
<template>
<div>
<span
v-for="(error, index) in props.errors"
:key="key(index)"
>
{{ error }}
</span>
</div>
</template>
<script setup>
const props = defineProps(['errors']);
const key = (index) => {
return `validation_error_${index}_${Math.random()}`;
}
</script>
During testing on my login form, I noticed that although the errors value is being updated in Vue Dev Tools, it is not being passed to the ValidationErrors
component.
Login.vue
<template>
<div>
<form action="#" method="POST">
<div>
<label for="email">Email Address</label>
<div>
<input
v-model="formData.email"
id="email"
name="email"
type="email"
</div>
<validation-errors :errors="errorFor('email')"></validation-errors>
</div>
<!-- ... -->
</template>
<script setup>
import { reactive } from 'vue';
import axios from 'axios';
import useErrorHandling from '../../Shared/Composable/useErrorHandling.js';
import ValidationErrors from '../../Components/Form/ValidationErrors.vue';
let { errors, errorFor } = useErrorHandling();
const formData = reactive({
email: "",
password: ""
});
const login = async () => {
axios
.post('/api/auth/login', {
email: formData.email,
password: formData.password
})
.then((response) => {
// Login user
})
.catch(error => {
errors = error.response.data.errors;
})
}
</script>
I am wondering how I can call the errorFor
function from within my Login.vue
form?