axios
라이브러리의 사용법을 중점적으로 살펴보겠습니다.npm install axios
src
폴더 밑에 api
폴더를 만들고 index.js
파일을 생성해 보겠습니다.import axios from 'axios';
// Axios 인스턴스를 생성합니다.
const api = axios.create({
// API 요청의 기본 주소를 설정합니다.
// 모든 요청 앞에 이 주소가 붙게 됩니다.
baseURL: 'https://jsonplaceholder.typicode.com'
});
export default api;
axios.get('https://jsonplaceholder.typicode.com/posts')
대신 api.get('/posts')
와 같이 짧고 간결하게 코드를 작성할 수 있습니다.onMounted
입니다.<script setup>
import { ref, onMounted } from 'vue';
import api from '@/api'; // 우리가 만든 Axios 인스턴스를 가져옵니다.
const posts = ref([]);
// onMounted 훅에 비동기 함수를 전달합니다.
onMounted(async () => {
try {
// 컴포넌트가 마운트되면 API를 호출하여 게시물 목록을 가져옵니다.
const response = await api.get('/posts?_limit=10'); // 10개만 가져오기
posts.value = response.data; // 응답 데이터를 posts 상태에 저장합니다.
} catch (error) {
console.error('데이터를 가져오는 중 에러 발생:', error);
}
});
</script>
<template>
<div>
<h1>게시물 목록</h1>
<ul>
<li v-for="post in posts" :key="post.id">
{{ post.title }}
</li>
</ul>
</div>
</template>
PostList
컴포넌트가 화면에 준비되자마자 /posts
API를 호출하고, 응답으로 받은 게시물 목록을 화면에 그려줍니다.try...catch...finally
구문을 사용하면 이 로직을 깔끔하게 구현할 수 있습니다.<script setup>
import { ref, onMounted } from 'vue';
import api from '@/api';
const posts = ref([]);
const isLoading = ref(false); // 로딩 상태를 관리할 ref
const error = ref(null); // 에러 상태를 관리할 ref
onMounted(async () => {
isLoading.value = true; // API 호출 시작 전에 로딩 상태를 true로 설정
error.value = null;
try {
// try 블록 안에서 API를 호출합니다.
const response = await api.get('/posts?_limit=10');
posts.value = response.data;
} catch (err) {
// catch 블록에서 에러를 처리합니다.
console.error('데이터를 가져오는 중 에러 발생:', err);
error.value = '데이터를 불러올 수 없습니다. 잠시 후 다시 시도해주세요.';
} finally {
// finally 블록은 성공/실패 여부와 관계없이 항상 실행됩니다.
isLoading.value = false; // API 호출이 끝나면 로딩 상태를 false로 설정
}
});
</script>
<template>
<div>
<h1>게시물 목록</h1>
<div v-if="isLoading">
로딩 중입니다...
</div>
<div v-else-if="error">
<p style="color: red;">{{ error }}</p>
</div>
<ul v-else>
<li v-for="post in posts" :key="post.id">
{{ post.title }}
</li>
</ul>
</div>
</template>
다음 'Vue 기본기 다지기 8편'에서는 컴포넌트의 스타일을 관리하는 방법과, 특정 조건에 따라 화면의 일부를 보여주거나 숨기는 조건부 렌더링에 대해 알아보겠습니다.