A modern Single Page Application (SPA) cannot function without dynamic data.
To get data from a database, Vue needs to communicate with a backend server or API.
While Vue does not have a built-in HTTP module, it works flawlessly with standard browser APIs.
The easiest way to perform an HTTP request in Vue is by using the native JavaScript fetch() API.
It is built directly into modern browsers and returns a JavaScript Promise.
You simply make the request, convert the response to JSON, and assign it to a reactive Vue variable.
<script setup>
import { ref } from 'vue'
const userData = ref(null)
function loadUser() {
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(data => {
userData.value = data
})
}
</script>
Instead of chaining .then() methods, many developers prefer using async and await.
This syntax makes asynchronous HTTP requests look exactly like standard, synchronous code.
async function loadUser() {
try {
const response = await fetch('https://api.example.com/data')
userData.value = await response.json()
} catch (error) {
console.error('API Request Failed!', error)
}
}
While fetch() is excellent, many enterprise teams prefer installing a library called Axios.
Axios automatically transforms JSON data, provides timeout features, and works identically on the Node.js backend.
If your application has heavy API dependencies, installing Axios via NPM is highly recommended!
Does Vue come with its own built-in module for making HTTP requests?
What method must you call on a fetch() response to convert it into a usable JavaScript object?