Vue.js는 JavaScript 프레임워크 중 하나로, 사용하기 쉽고 유연한 기능을 제공합니다. 이번 포스트에서는 Vue.js를 사용하여 뉴스 앱을 개발하는 방법에 대해 알아보겠습니다.
개요
이 뉴스 앱은 외부 API를 사용하여 최신 뉴스를 가져와서 보여줍니다. 사용자는 카테고리를 선택하고, 관심 있는 뉴스 기사를 읽을 수 있습니다.
프로젝트 설정
Vue.js를 사용하여 뉴스 앱을 개발하기 위해 먼저 프로젝트를 설정해야 합니다. 다음 명령어를 사용하여 Vue CLI를 설치합니다.
npm install -g @vue/cli
프로젝트를 생성하려면 다음 명령어를 실행합니다.
vue create news-app
이제 프로젝트 디렉토리로 이동하여 개발을 시작할 수 있습니다.
API 요청
뉴스 앱에서는 외부 API를 사용하여 뉴스를 가져옵니다. 예를 들어, News API를 사용할 수 있습니다.
const API_KEY = 'YOUR_API_KEY';
axios.get(`https://newsapi.org/v2/top-headlines?country=kr&apiKey=${API_KEY}`)
.then(response => {
console.log(response.data.articles);
})
.catch(error => {
console.error(error);
});
위의 예시 코드에서는 axios
라이브러리를 사용하여 API 요청을 보내고, 응답을 핸들링합니다. YOUR_API_KEY
에는 사용자의 API 키를 입력해야 합니다.
컴포넌트 개발
Vue.js에서는 컴포넌트 기반으로 애플리케이션을 개발합니다. 뉴스 앱에서는 다음과 같은 컴포넌트를 개발할 수 있습니다.
NewsList.vue
<template>
<div class="news-list">
<ul>
<li v-for="article in articles" :key="article.title">
<h2>{{ article.title }}</h2>
<p>{{ article.description }}</p>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['articles'],
};
</script>
<style scoped>
.news-list {
margin-top: 20px;
}
h2 {
font-size: 18px;
font-weight: bold;
}
p {
font-size: 14px;
}
</style>
NewsCategory.vue
<template>
<div class="news-category">
<select v-model="selectedCategory">
<option v-for="category in categories" :value="category">{{ category }}</option>
</select>
<button @click="fetchNews">Load News</button>
</div>
</template>
<script>
export default {
data() {
return {
selectedCategory: '',
categories: ['business', 'entertainment', 'health', 'science', 'sports', 'technology'],
};
},
methods: {
fetchNews() {
this.$emit('fetch-news', this.selectedCategory);
},
},
};
</script>
<style scoped>
.news-category select, .news-category button {
margin-right: 10px;
}
</style>
App.vue
<template>
<div class="app">
<h1>News App</h1>
<NewsCategory @fetch-news="fetchNews"></NewsCategory>
<NewsList :articles="articles"></NewsList>
</div>
</template>
<script>
import NewsCategory from './components/NewsCategory.vue';
import NewsList from './components/NewsList.vue';
export default {
components: {
NewsCategory,
NewsList,
},
data() {
return {
articles: [],
};
},
methods: {
fetchNews(category) {
// API 요청 및 응답 처리 로직
},
},
};
</script>
<style scoped>
.app {
margin: 20px;
}
h1 {
font-size: 24px;
font-weight: bold;
}
</style>
실행
모든 컴포넌트를 개발하고 파일을 정리하였다면, 앱을 실행해보겠습니다.
npm run serve
웹 브라우저에서 http://localhost:8080
을 열면 뉴스 앱을 확인할 수 있습니다.
결론
Vue.js를 사용하여 뉴스 앱을 개발하는 방법에 대해 알아보았습니다. 이를 통해 Vue.js의 간편한 개발 방식과 컴포넌트 기반 아키텍처의 장점을 경험할 수 있습니다. Vue.js를 사용하여 다양한 애플리케이션을 개발해보세요!