Table of Contents
In this tutorial we're going to learn how we can create a VueJS component for a contact form and create a Laravel API Endpoint that will send the message from the contact form.
VueJS Contact Component
First we're going to build our VueJS component, this goes into your resources/assets/js/components/
directory. The HTML for the contact form is very simple we just have a name, email, message and a submit button. You'll notice on the form
tag we have a submit event to run the submitForm method v-on:submit.prevent="submitForm"
. The second thing you'll notice is that on each of the form elements we want to collect data on we have a v-model
attribute. In the script section of our component we need to define the form element we want to collect data from in the data section of the component.
data(){
return{
name:'',
email:'',
message:''
}
},
Above we said on the submit of form we call the submitForm
method, this will collect the form data and send a post request to the route api/contact
using axios which in turn will send an email on the back-end.
methods: {
submitForm(){
let formData = {
name:this.name,
email:this.email,
message:this.message,
};
return axios.post('/api/contact', formData).then(data => {
// Change to notify the user
console.log('Message sent');
});
}
}
Below is the full contact form component.