자바스크립트

Vue.js에서 axios 로 비동기 통신

마리오64 2019. 8. 7. 01:00

#설치

Vue cli 에서는

vue add axios

Vue cli로 시작한 프로젝트가 아니라면

터미널에서 npm으로 axios 를 설치합니다.

axios는 비동기통신을 하기위한 라이브러리이며

return 값은프로미스 객체형태입니다.

npm i axios

package.json이 있는 프로젝트폴더에서

import axios from 'axios'
Vue.prototype.$axios = axios

main.js 에 axios 모듈을 Vue의 프로토타입에 등록해서 사용할 수있습니다.

<template>
  <div id="board">
    <table>
      <thead>
        <tr>
          <th scope="col">글번호</th>
          <th scope="col">제목</th>
          <th scope="col">내용</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="article in posts" :key="article.boardNum">
          <td>{{article.boardNum}}</td>
          <td>{{article.title}}</td>
          <td>{{article.content}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

template 을 이용하여 재사용 합시다.

<script>
export default {
  name: 'board',
  data() {
    return {
      posts: []
    }
  },
  methods: {
    listBoard: function(){
      this.$http.get('/list/read', {
        headers: {
          'Accept' : 'application/json'
        }
      })
      .then(response => {
        this.posts = response.data;
        console.log(response)
      })
      .catch(e => console.log("e"))
    }
  },
  mounted() {
   this.listBoard();
  }
}
</script>

this.$axios 사용할 수있습니다.

서버에서 JSON 형식의 데이터를 받는데

response 객체에 데이터 속성에 있습니다.

response.data 로 접근하면됩니다.