This Vue component uses Axios to get posts from a public API when it loads. It shows loading text, errors, or the list of posts.
<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 8000,
headers: { 'Content-Type': 'application/json' }
});
const posts = ref([]);
const error = ref(null);
const loading = ref(true);
onMounted(async () => {
try {
const response = await apiClient.get('/posts');
posts.value = response.data;
} catch (err) {
error.value = 'Failed to load posts';
} finally {
loading.value = false;
}
});
</script>
<template>
<main>
<h1>Posts</h1>
<p v-if="loading">Loading posts...</p>
<p v-if="error" role="alert" style="color: red">{{ error }}</p>
<ul v-if="!loading && !error">
<li v-for="post in posts" :key="post.id">
<strong>{{ post.title }}</strong><br />
{{ post.body }}
</li>
</ul>
</main>
</template>