SPA/Vue
vue.js axios 설치 및 간단한 API 등록
memeseo
2021. 5. 10. 18:08
1. axios 설치
npm i axios --save
2. views 폴더 NewsView.vue파일에 axios 등록 및 API 사용
[api 구현하고자 하는 components 파일에 axios 등록하면 됨]
<template>
<div>
<div v-for="user in users" :key="user">{{ user.title }}</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data(){
return {
users: []
}
},
created(){
axios.get('https://api.hnpwa.com/v0/news/1.json')
.then(response => this.users = response.data)
.catch(error => console.log(error))
},
/*
위 화살표 함수와 동일한 코드 ▼
axios.get('https://api.hnpwa.com/v0/news/1.json')
.then(function(response){
this.users = response.data
})
.catch(function(error){
console.log(error)
});
*/
}
</script>
But,
component마다 api를 호출해서 쓰는게 아닌 일괄적으로 api 폴더를 만들어서 관리!
src에다가 api 폴더 만들고 실습하는건 커밍순 ,,