[vue.js] 프로젝트에 axios 적용하기

Language/Vue.js|2021. 8. 19. 13:44

소개

Axios는 브라우저 및 node.js를 위한 간단한 비동기 통신 HTTP 클라이언트입니다. Axios는 매우 확장 가능한 인터페이스를 가진 작은 패키지로 사용하기 쉬운 라이브러리를 제공합니다.

 

브라우저에 내장되어 있는 fetch 와 비교한 표입니다.

axios vs fetch 

Axios Fetch
요청 객체에 url이 있습니다. 요청 객체에 url이 없습니다.
써드파티 라이브러리로 설치가 필요합니다. 현대 브라우저에 기본 탑재되어 별도  설치가 필요 없습니다.
XSRF(크로사 사이트 위조) 보호 기능이 있습니다. 별도 보호 기능이 없습니다.
data 속성을 사용합니다. body 속성을 사용합니다.
data는 object를 포함 합니다. body는 문자열화 되어있습니다.
status가 200이고 statusText가 ‘OK’이면 성공 입니다. 응답객체가 ok 속성을 포함하면 성공 입니다.
자동으로 JSON데이터 형식으로 변환됩니다. .json()메서드를 사용해야 합니다.
요청을 취소할 수 있고 타임아웃을 걸 수 있습니다. 해당 기능 존재 하지않습니다.
HTTP 요청을 가로챌수 있습니다. 기본적으로 제공하지 않습니다.
download진행에 대해 기본적인 지원을 합니다. 지원하지 않습니다.
많은 브라우저를 지원합니다. Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+이상에 지원합니다.

axios가 좀더 많은 기능을 제공해 줍니다. 그래서 인지 가장 많이 사용합니다.

 

설치

yarn add axios

main.js  파일 수정

import Vue from 'vue'
import Element from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from './router'
import '@fortawesome/fontawesome-free/js/all.js'
import axios from "axios";
import App from './App.vue'
 
Vue.prototype.$axios = axios;
Vue.config.productionTip = false
Vue.use(Element, { size: 'small', zIndex: 3000 });
 
new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

예제 (행정코드)

법정 행정 코드를 다운로드 받아서 csv 파일을 만들고 이를 axios로 불러와서 행정동을 선택하는 예제를 만들어 보겠습니다. 

 

components/LawCode.vue 파일을  생성하고 아래와 같이 코딩합니다.

<template>
  <div>
    <el-row style="width:800px">
      <el-col :span="6">
        <el-select v-model="cate1" @change="chgCate1" placeholder="시/도">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-select v-model="cate2" @change="chgCate2" placeholder="시/군/구">
          <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-select v-model="cate3" @change="chgCate3" placeholder="읍/면/동">
          <el-option
              v-for="item in options3"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-select v-model="cate4" @change="chgCate4" placeholder="리">
          <el-option
              v-for="item in options4"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-col>
    </el-row>
  </div>
</template>
 
<script>
const URL = "https://onehit9.github.io/";
 
export default {
  name: "LawCode",
  created() {
    this.getData();
  },
  data() {
    return {
      rows: [],
      options: [],
      options2: [],
      options3: [],
      options4: [],
      cate1: "",
      cate2: "",
      cate3: "",
      cate4: "",
      lastCate: "",
    }
  },
  methods: {
    resetCate(level) {
      if (level < 3) {
        this.cate2 = "";
        this.options2 = [];
      }
      if (level < 4) {
        this.cate3 = "";
        this.options3 = [];
      }
      if (level < 5) {
        this.cate4 = "";
        this.options4 = [];
      }
    },
 
    chgCate(cateNm,idx) {
      this.resetCate(idx - 1);
      let options = [];
      let cate = this.rows.filter(
          row => row.split(",")[idx] == "" &&
              (cateNm == "" ? true : row.split(",")[idx-1] != "" && row.split(",")[idx-2] == cateNm)
      );
      cate.map(cate => options.push({
        value: cate.split(",")[0],
        label: cate.split(",")[idx - 1]
      }))
      return options;
    },
 
    getData() {
      this.$axios.get(URL + 'apt/' + 'law_code.csv', {params: {}})
          .then((response) => {
            this.rows = response.data.replace(/["]+/g, "").split("\n");
            this.options = this.chgCate("",2);
          });
    },
    chgCate1() {
      this.lastCate = this.cate1;
      let cateNm = this.options[this.options.findIndex(e => e.value === this.cate1)].label;
      this.options2 = this.chgCate(cateNm,3);
    },
    chgCate2() {
      this.lastCate = this.cate2;
      let cateNm = this.options2[this.options2.findIndex(e => e.value === this.cate2)].label;
      this.options3 = this.chgCate(cateNm,4);
    },
    chgCate3() {
      this.lastCate = this.cate3;
      let cateNm = this.options3[this.options3.findIndex(e => e.value === this.cate3)].label;
      this.options4 = this.chgCate(cateNm,5);
    },
    chgCate4() {
      this.lastCate = this.cate4;
    },
  }
}
</script>
<style scoped></style>

위코드에서 중요한 부부은 104~110라인의 getData() 부분으로 axios를 이용해서 law_code.csv를 가져오는 부분입니다.

 

실행결과

 

댓글()