본문 바로가기
SPA/Vue

axios의 api 함수 구조화 방법 [예시O]

by memeseo 2021. 5. 11.

 

1. api 폴더 생성 후 index 파일 생성

: 많은 api 관리 및 axios를 한 번만 호출하기 위함

import axios from 'axios';

//1. HTTP Request & Response와 관련된 기본 설정
const config = {
    baseURL : 'https://api.hnpwa.com/v0/'
};

// 2. API 함수들을 정리
function fetchNewsList(){
    return axios.get(config.baseURL + 'news/1.json'); // return해주는게 중요!
    // return axios.get(`${config.baseURL}news/1.json`); ES6이용해서 이런 코드 작성도 가능
}

function fetchJobsList(){
    return axios.get(config.baseURL + 'jobs/1.json');
}

function fetchAskList(){
    return axios.get(config.baseURL + 'ask/1.json');
}

export {
    fetchNewsList,
    fetchJobsList,
    fetchAskList
}

* return axios.get(`${config.baseURL}jobs/1.json`);

config를 불러오는 기호는 (`) 백틱임 작은 따옴표(')아님 

 

 

2. api가 필요한 해당 components에서 사용

<template>
  <div>
       <div v-for="list in jobsList" :key="list">{{list}}}</div>
  </div>
</template>

<script>
import { fetchJobsList } from '../api/index.js'

export default {
  data(){
    return {
      jobsList : []
    }
  },

  created() {
    fetchJobsList()
    .then( response => this.jobsList = response.data )
    .catch( error => console.log(error))
  }
}
</script>