React에서 하던 방식의 axios를 vue.js에서 살펴보고 components 방식으로도 살펴봅니다.
npm i axios --save
설치
// 기존의 사용되는 axios get 방식의 api <template> <div v-for="user in users">{{ user }}</div> </template> <script> import axios from 'axios' export default { name: "NewsView", data(){ return{ users: [] } }, created() { axios.get('users') .then(res => this.users = res.data) .catch() } } </script> <style lang="scss" scoped> </style>
api
commponents 생성import axios from 'axios'; const config = { baseUrl: 'https://api.hnpwa.com/v0/' } function fetchNewsList() { return axios.get(`${config.baseUrl}news/1.json`); } export { fetchNewsList }
api
생성후 importimport { fetchNewsList } from '../api/index' export default { name: "NewsView", data(){ return{ users: [] } }, created() { fetchNewsList() .then(res => this.users = res.data) .catch() } }
[ 정상적인 API 결과 ]