0
0
Vueframework~30 mins

POST requests for form submission in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
POST requests for form submission
📖 Scenario: You are building a simple contact form on a website. When a user fills in their name and message, the form should send this data to a server using a POST request.
🎯 Goal: Create a Vue component that collects user input for name and message, then sends this data as a POST request when the form is submitted.
📋 What You'll Learn
Use Vue 3 Composition API with <script setup>
Create reactive variables for form data
Add a function to handle form submission
Send form data as JSON using fetch with POST method
Bind form inputs to reactive variables
Use semantic HTML form elements with accessibility in mind
💡 Why This Matters
🌍 Real World
Forms are everywhere on websites and apps. Sending data with POST requests is how user input reaches servers for processing.
💼 Career
Understanding form submission and POST requests is essential for frontend developers working with APIs and building interactive web applications.
Progress0 / 4 steps
1
Set up reactive form data
Inside a <script setup> block, import ref from 'vue' and create two reactive variables called name and message, both initialized as empty strings.
Vue
Need a hint?

Use import { ref } from 'vue' and then const name = ref('') and const message = ref('').

2
Add a submit handler function
Add a function called submitForm inside the <script setup> block. This function should prevent the default form submission behavior by accepting an event parameter and calling event.preventDefault().
Vue
Need a hint?

Define function submitForm(event) and call event.preventDefault() inside it.

3
Send form data with POST request
Inside the submitForm function, add code to send a POST request to 'https://example.com/api/contact' using fetch. The request should have headers specifying 'Content-Type': 'application/json' and the body should be a JSON string containing name.value and message.value. Use await and mark submitForm as async.
Vue
Need a hint?

Use await fetch with method 'POST', headers for JSON, and body: JSON.stringify({ name: name.value, message: message.value }).

4
Bind inputs and connect submit handler
In the