Vue Axios Form Submit

User
form submit in vue axois
Assistant
In Vue 3, you can use Axios to submit a form using either the `v-model` directive to bind input fields or the `FormData` object for file uploads. Here's a basic example of how to submit a form using Axios in Vue 3:

### **1. Install Axios (if not installed)**
If you haven't installed Axios yet, you can install it via Yarn:

yarn add axios

or using npm:

npm install axios

### **2. Basic Form Submission Example**
Here’s a simple example of how to handle form submission with Axios in Vue 3:

#### **Vue Component (`FormComponent.vue`)**

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const formData = ref({
  name: '',
  email: '',
  message: ''
});

const submitForm = async () => {
  try {
    const response = await axios.post('/api/contact', formData.value);
    alert('Form submitted successfully: ' + response.data.message);
  } catch (error) {
    console.error('Error submitting form:', error.response?.data || error.message);
  }
};
</script>

<template>
  <form @submit.prevent="submitForm">
    <label>Name:</label>
    <input v-model="formData.name" type="text" required />

    <label>Email:</label>
    <input v-model="formData.email" type="email" required />

    <label>Message:</label>
    <textarea v-model="formData.message" required></textarea>

    <button type="submit">Submit</button>
  </form>
</template>

### **3. Using `FormData` for File Upload**
If your form includes file uploads, use the `FormData` object.

#### **Updated Vue Component (`FormWithFileUpload.vue`)**

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const name = ref('');
const file = ref(null);

const handleFileChange = (event) => {
  file.value = event.target.files[0];
};

const submitForm = async () => {
  const formData = new FormData();
  formData.append('name', name.value);
  formData.append('file', file.value);

  try {
    const response = await axios.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    alert('File uploaded successfully: ' + response.data.message);
  } catch (error) {
    console.error('Error uploading file:', error.response?.data || error.message);
  }
};
</script>

<template>
  <form @submit.prevent="submitForm">
    <label>Name:</label>
    <input v-model="name" type="text" required />

    <label>Upload File:</label>
    <input type="file" @change="handleFileChange" required />

    <button type="submit">Upload</button>
  </form>
</template>

### **4. Backend Route Example (Laravel)**
If you’re using Laravel, define a route in `routes/api.php`:

use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;

Route::post('/contact', function (Request $request) {
    $request->validate([
        'name' => 'required|string',
        'email' => 'required|email',
        'message' => 'required|string',
    ]);
    return response()->json(['message' => 'Form submitted successfully!']);
});

Route::post('/upload', function (Request $request) {
    $request->validate([
        'name' => 'required|string',
        'file' => 'required|file|max:2048',
    ]);
    $filePath = $request->file('file')->store('uploads', 'public');
    return response()->json(['message' => 'File uploaded!', 'path' => $filePath]);
});

### **5. Notes**
✅ Use `@submit.prevent="submitForm"` to prevent default form submission.
✅ Use `v-model` to bind input values to Vue state.
✅ For files, use `FormData` to append data properly.
✅ Use try/catch blocks to handle errors and display proper feedback.

Would you like to integrate this with Inertia.js? 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *