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>
'SPA > Vue' 카테고리의 다른 글
라우터 params를 이용한 user 상세페이지 구현 (예시O) (0) | 2021.05.12 |
---|---|
axios를 이용한 api호출 vuex로 모듈화 하기 (예시O) (0) | 2021.05.11 |
vue.js axios 설치 및 간단한 API 등록 (0) | 2021.05.10 |
vuejs 라우터 설치 및 구현 (0) | 2021.05.10 |
Vue CLI 2.x / CLI 3.x 비교 (0) | 2021.05.10 |