Episode 33 of 44

GET Requests

Fetch and display data from an API using GET requests — create a blog list component that loads posts on mount.

GET Requests

Let us build a component that fetches blog posts from an API and displays them in a list. This is the most common API interaction in any front-end application.

The Blog List Component

<template>
    <div id="blog-list">
        <h2>Blog Posts</h2>
        <div v-for="blog in blogs" :key="blog.id" class="blog-card">
            <h3>{{ blog.title }}</h3>
            <p>{{ blog.body | snippet }}</p>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            blogs: []
        };
    },
    created() {
        this.$http.get('https://jsonplaceholder.typicode.com/posts')
            .then(response => {
                this.blogs = response.body.slice(0, 10);
            });
    },
    filters: {
        snippet(value) {
            return value.slice(0, 100) + '...';
        }
    }
};
</script>

<style scoped>
.blog-card { padding: 20px; margin: 10px 0; background: #f4f4f4; border-left: 4px solid #42b883; }
.blog-card h3 { color: #333; text-transform: capitalize; }
</style>

Loading State

<template>
    <div>
        <p v-if="loading">Loading posts...</p>
        <div v-else v-for="blog in blogs" :key="blog.id">
            <h3>{{ blog.title }}</h3>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return { blogs: [], loading: true };
    },
    created() {
        this.$http.get('https://jsonplaceholder.typicode.com/posts')
            .then(response => {
                this.blogs = response.body.slice(0, 10);
                this.loading = false;
            });
    }
};
</script>

Key Takeaways

  • Fetch data in the created hook — the component's data is ready but the DOM is not yet mounted
  • Use a loading flag to show a loading state while the request is in progress
  • Render fetched data with v-for — Vue reactivity updates the DOM when the data arrives