Vue.js에서 Axios 사용하기

입문자를 위한 Vue.js + Axios 튜토리얼


Vue.js 로고

Axios는 HTTP 통신과 AJAX 요청을 다루는 라이브러리입니다. 비슷한 역할을 하는 vue-resource도 있지만, 업데이트 주기가 느리고 커뮤니티가 작아서 요즘은 잘 쓰지 않는 편이라고 합니다.

Axios 설치

다음 명령으로 Axios를 설치합니다.

npm install --save axios

그리고 main.js에 메소드를 추가해 Axios를 전역에서 사용할 수 있도록 합니다.

import Vue from 'vue'
import App from './App'
import axios from 'axios'

Vue.prototype.$http = axios

app = new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

Axios 사용

JSONPlaceholder라는 서비스를 사용해 방금 설치한 Axios를 테스트해 보겠습니다. 아래 코드를 복사·붙여넣기 해보세요.

<template lang="pug">
  div#app
    div(
      v-for="user in users"
      :key="users.id"
    )
      h1 {{ user.name }}
      p {{ user.email }}
    button(@click="fetchUsers") Click me!
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      users: []
    }
  },
  methods: {
    fetchUsers: function () {
      const baseURI = 'https://jsonplaceholder.typicode.com/users'
      this.$http.get(baseURI)
      .then((result) => {
        this.users = result.data
      })
    }
  }
}
</script>
  
<style lang="scss">
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: left;
  width: 640px;
  margin: 0 auto;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Internet Explorer

IE는 Promise를 지원하지 않으므로 es6-promise 폴리필이 필요할 수 있습니다. 다음 명령으로 설치합니다.

npm install --save es6-promise

그리고 webpack 설정 파일에 아래 한 줄을 추가합니다.

require('es6-promise').polyfill();

마치며

Vue.js + Axios에 대한 짧은 튜토리얼이 도움이 되었기를 바랍니다. 연락은 LinkedIn이나 ghsspower@gmail.com으로 부탁드립니다. 감사합니다!

제목 : Vue.js에서 Axios 사용하기
일자 : 2018년 8월 5일
작성자 : Hyouk Seo (Spemer)