vue.js/vue.js 2

55. <vue-news> 프로젝트 | axios | .then(성공) | .catch(실패) | API 가져오기

DEV-Front 2022. 8. 5. 14:40
반응형


api 폴더의 <index.js>

import axios from 'axios';


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

// 2. 공통 API 함수들 정리
function fetchNewsList(){
    // return 바로 해준게 핵심
    // return axios.get(config.baseUrl+'/news/1.json');
    return axios.get(`${config.baseUrl}news/1.json`);
}

function fetchJobsList(){
    return axios.get(`${config.baseUrl}jobs/1.json`)
}

function fetchAskList() {
    return axios.get(`${config.baseUrl}ask/1.json`)
}

// 3. 마지막 내보내기
export { fetchNewsList, fetchJobsList, fetchAskList }

<NewsView.vue>

ES5 식으로 사용

<template>
    <div>
        <!-- v-bind:key 에는 객체 넣을수없고 숫자, 문자만 넣을수 있다 -->
        <div v-for="(user, i) in users" v-bind:key="i">{{ user.title }} {{ i }}</div>
    </div>
</template>

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


export default {
    data(){
        return{
            users:[]
        }
    },
    created(){
        var vm = this;
        fetchNewsList()        
        .then(function(response){
            console.log(response);
            vm.users = response.data;
        })
        .catch(function(error){
            console.log(error);
            })
    }
};
</script>

<style lang="scss" scoped>

</style>

<AskView.vue>

ES6 식으로 사용

<template>
    <div>
        <div v-for="(ask, i) in asks" v-bind:key="i"> {{ ask.title}} </div>
    </div>
</template>

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

export default {
    data(){
        return{
            asks: []
        }       
    },
   created(){
     fetchAskList()
     .then(res => this.asks = res.data)
     .catch(error => console.log(error));
   }
};
</script>

<style lang="scss" scoped>

</style>

<JobsView.vue>

ES6 식으로 사용

<template>
    <div>
        <div v-for="(job, i) in jobs" v-bind:key="i">{{ job.title }}</div>
    </div>
</template>

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

export default {
    data() {
        return {
            jobs: []
        };
    },
    created(){
         fetchJobsList()
            .then(res => this.jobs = res.data)
            .catch(error => console.log(error));
    }
};
</script>

<style lang="scss" scoped>

</style>
반응형