# 3. API 구현 ###### tags: `지호`, `Vue.js 완벽 가이드` --- ## 1. axios를 이용한 api 호출 ### 구조화 필요 이유 - /views 안에 컴포넌트들은 비즈니스 로직이 들어가지 않는 것이 좋음 - 각 컴포넌트마다 api 라이브러리를 호출하면 좋지 않음 - 중복된 코드 <br/> ### LifeCycle Hook - created, beforeMount에 데이터를 불러오는 것이 좋음 - mounted가 되고 난 이후에 데이터를 가져오면 뷰의 리액티브 시스템 때문에 뷰를 다시 그리게 됨 참고: https://v2.vuejs.org/v2/guide/reactivity.html?redirect=true#ad <br/> src/api/index.js ![](https://i.imgur.com/XQjZRf3.png) src/views/JobsView.vue ![](https://i.imgur.com/2hsLZyx.png) <br/> ## 2. 자바스크립트 this 4가지와 화살표 함수의 this ### this 1. Window 객체 (전역 변수 관리) 2. 특정 함수 안에서의 this도 Window 객체를 가리킴 3. Vue 객체 안에서의 this는 생성자 함수를 가리킴 4. 비동기 처리에서의 this - 자바스크립트는 비동기 호출을 할 때 기존의 this와 다른 범위가 this가 생겨서, 바인딩을 해줘야함 - ES6의 화살표 함수는 이 바인딩을 해줄 필요가 없이 this를 계속 동일하게 만들어줌 ```javascript= // 1 console.log(this); //2 function sum(a, b) { console.log(this); } sum(1, 2) //3 function Vue(el) { consolle.log(this); } new Vue('#app'); //4 var vm = this; console.log(this); fetchNewsList() .then(function(response) { console.log(this); vm.users = response.data; }) .catch(function(error) { console.log(error); }) //화살표 함수 이용 console.log(this); fetchNewsList() .then((response) => { console.log(this); this.users = response.data; }) .catch(function(error) { console.log(error); }) ``` 참고 https://joshua1988.github.io/web-development/javascript/promise-for-beginners/ https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise