본문 바로가기
FrontEnd/Vue 2

[Vue.js] Axios 라이브러리

by Chaedie 2022. 9. 18.
728x90

Axios 서론

  • SPA 프레임워크와 관계없이 가장 많이 쓰이는 것으로 알려진 AXIOS 라이브러리입니다.
  • 부트캠프에서 React를 배울 당시 Axios를 쓰지않고, Fetch만을 사용해서 구현해보라는 제한사항이 있었습니다.
  • 따라서 저는 Axios 사용이 처음입니다.
  • 뷰에서는 Axios를 사용하라는 권고가 있습니다. axios이전엔 vue-resourse라는 라이브러리가 공식이었다고 하네요.

Axios 사용법 (with 오픈소스 사용법)

Axios 예제

  • 아래의 Axios 사용예제를 따라 쳐본 결과 fetch와 사용법이 거의 같다는걸 알게 되었다.
  • 다른점은 fetch에서는 첫번째 then에서 response.json() 해주는 부분이 필요한데, axios에서는 그 부분이 없었다.
  • 구글링을 통해 fetch와 axios를 검색해보면 이런 저런 사소한 차이점들이 있다.
  • 우선은 거의 같은 기능을 하는 HTTP 통신 API이고, fetch는 내장 라이브러리, axios는 import 가 필요한 라이브러리 라고 것만 알고, axios가 이런저런 장점이 더 있다고 생각하면 될것 같다.
  • react에서 fetch를 사용할 땐 then()안에서 setState()를 사용하면 data set이 되었는데, Vue에서 데이터를 받아올땐, this.foo = bar; 로 직접 세팅해줘야한다. 그래서 this가 중요한데, 화살표 함수가 없는 이번 예제에선 단순히 let vm = this;로 세팅한 뒤 then 안에서 vm.users 해주는것으로 해결하였다.
  • 면접장에서 this를 많이 물어본다고 하는데, 이렇게 실 사용예제들을 많이 접한 뒤 면접 준비 하면 잘 알게되겠죠? ㅎㅎ
  • fetch와 axios의 차이에 대해 한 눈에 볼 수 있는 링크입니다. 링크
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <button v-on:click="getData">get user</button>
      <div>{{users}}</div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
      new Vue({
        el: '#app',
        data: {
          users: [],
        },
        methods: {
          getData: function () {
            let vm = this;

            axios
              .get('https://jsonplaceholder.typicode.com/users/')
              .then(function (response) {
                console.log(response.data);
                // 여기서의 this는 getData에서의 this와 다르다.
                // 실행 컨텍스트가 바뀌기 때문에 this도 달라진다.
                // this.users = response.data;
                vm.users = response.data;
              })
              .catch(function (error) {
                console.log(error);
              });
          },
        },
      });
    </script>
  </body>
</html>

댓글