๐ฏ ํ์ต ๋ชฉํ
- Axios๋ฅผ ์ค์นํ๊ณ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ์ตํ๋ค.
- ์ธ๋ถ API๋ก๋ถํฐ ๋ฐ์ดํฐ๋ฅผ ๋ฐ์์ Vue ์ฑ์ ๋ ๋๋งํ๋ค.
โ 1. Axios ์ค์น
Vue CLI ํ๋ก์ ํธ์์ Axios๋ ๋ณ๋ ์ค์น๊ฐ ํ์ํฉ๋๋ค.
npm install axios
์ค์น ํ, src/App.vue
๋๋ ๋ณ๋ API ๋ชจ๋์์ import axios from 'axios'
์ฌ์ฉ
โ 2. ์ฌ์ฉํ ์ธ๋ถ API
JSONPlaceholder์์ ์ ๊ณตํ๋ ์ํ API๋ฅผ ์ฌ์ฉํ ๊ฒ์ ๋๋ค:
https://jsonplaceholder.typicode.com/todos?_limit=5
์ด API๋ ๊ฐ์ง ํ ์ผ(todos) ๋ฐ์ดํฐ๋ฅผ JSON์ผ๋ก ๋ฐํํฉ๋๋ค.
๐ป ์ค์ต: API๋ก ํ ์ผ ๋ชฉ๋ก ๋ถ๋ฌ์ค๊ธฐ
โ
App.vue
<template>
<div class="todo-container">
<h2>๐ก ์ธ๋ถ์์ ๋ถ๋ฌ์จ ํ ์ผ ๋ชฉ๋ก</h2>
<button @click="fetchTodos">๋ถ๋ฌ์ค๊ธฐ</button>
<ul class="todo-list">
<TodoItem
v-for="todo in todos"
:key="todo.id"
:content="todo.title"
@delete="removeTodo(todo.id)"
/>
</ul>
</div>
</template>
<script>
import axios from 'axios'
import TodoItem from './components/TodoItem.vue'
export default {
components: { TodoItem },
data() {
return {
todos: []
}
},
methods: {
async fetchTodos() {
try {
const res = await axios.get(
'https://jsonplaceholder.typicode.com/todos?_limit=5'
)
this.todos = res.data
} catch (err) {
alert('๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ค๋ ๋ฐ ์คํจํ์ต๋๋ค.')
}
},
removeTodo(id) {
this.todos = this.todos.filter(todo => todo.id !== id)
}
}
}
</script>
<style scoped>
.todo-container {
max-width: 480px;
margin: 40px auto;
padding: 24px;
border: 1px solid #ccc;
border-radius: 12px;
background: #f9f9f9;
box-shadow: 0 4px 10px rgba(0,0,0,0.05);
}
h2 {
text-align: center;
margin-bottom: 20px;
}
button {
display: block;
margin: 0 auto 20px;
padding: 8px 16px;
background-color: #2196f3;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
}
button:hover {
background-color: #1976d2;
}
</style>
โ ์คํ ๊ฒฐ๊ณผ
๋ถ๋ฌ์ค๊ธฐ
๋ฒํผ ํด๋ฆญ ์ ์ธ๋ถ API์์ ํ ์ผ 5๊ฐ๋ฅผ ๋ถ๋ฌ์ ๋ชฉ๋ก์ ํ์- ๊ฐ ํญ๋ชฉ์
TodoItem
์ปดํฌ๋ํธ๋ก ๋ ๋๋ง๋๋ฉฐ, ์ญ์ ๋ ๊ฐ๋ฅ
๐ง ๊ฐ๋ ์์ฝ
๊ฐ๋ | ์ค๋ช |
---|---|
axios.get(url) |
๋น๋๊ธฐ GET ์์ฒญ์ ๋ณด๋ |
await / async |
์๋ต์ ๊ธฐ๋ค๋ฆฐ ๋ค ๊ฒฐ๊ณผ ์ฒ๋ฆฌ |
v-for |
API๋ก๋ถํฐ ๋ฐ์ ๋ฐฐ์ด์ ๋ฐ๋ณต ๋ ๋๋ง |
filter() |
ํน์ ์์ดํ ์ญ์ ์ ์ฌ์ฉ |
โ ๋ง๋ฌด๋ฆฌ
- Axios๋ Vue์์ ๊ฐ์ฅ ๋ง์ด ์ฌ์ฉํ๋ HTTP ํต์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋๋ค.
- ์ธ๋ถ API ์ฐ๋์ ์ค์ ์ฑ์์ ๊ฑฐ์ ํ์์ ์ธ ๊ธฐ์ ์ ๋๋ค.
- ์๋ฌ ์ฒ๋ฆฌ๋ฅผ ํตํด ์ฌ์ฉ์์๊ฒ ์คํจ ์๋ฆผ์ ์ค ์๋ ์์ต๋๋ค.
๐ฌ ๋๊ธ
โป ๋ก๊ทธ์ธ ํ ๋๊ธ์ ์์ฑํ ์ ์์ต๋๋ค.