axios & mixin

채윤·2022년 6월 19일
0

axios

  • get - 서버에 데이터 호출해 조회할 경우
  • post - 데이터를 저장하기 위해 새로운 데이터를 넣어줄 경우
  • delete - 데이터를 삭제하는 용도로 서버 호출할 경우
  • put - 데이터 수정할 경우

ServerData.vue

  methods: {
    async api(url, method, data) {
      //url, 호출하는 방식, 서버로 던질 데이터
      return await axios({
        method: method,
        url: url,
        data: data,
      }).catch((e) => {
        console.log(e);
      }).data;
    },
  },

mixin을 사용하게 되면, method안에 들어가게 된다.

  • 믹스인은 믹스인 파일을 호출해서 사용하는 컴포넌트 안에 들어와 믹스인 되는 것을 뜻한다.
  • 오버라이딩, 코드 중복, 사용하지 않는 함수가 믹스인에 정의 되어 있는 문제점이 발생하게 된다.
methods: {
    async getProductList() {
      this.productList = await this.api(
        "https://cfa2c3ca-22ae-413f-ba6f-df81768325db.mock.pstmn.io/productList",
        "get",
        {}
      );
      console.log(this.productList);
    },
    async api(url, method, data) {
      //url, 호출하는 방식, 서버로 던질 데이터
      return await axios({
        method: method,
        url: url,
        data: data,
      }).catch((e) => {
        console.log(e);
      }).data;
    },
  },

MixinTest.vue

<template>
  <div>
    <button type="button" @click="getProductList">조회</button>
    <table>
      <thead>
        <tr>
          <th>제품명</th>
          <th>가격</th>
          <th>배송료</th>
          <th>카테고리</th>
        </tr>
      </thead>
      <tbody>
        <tr :key="i" v-for="(product, i) in productList">
          <td>{{ product.product_name }}</td>
          <td>{{ product.price }}</td>
          <td>{{ product.delivery_price }}</td>
          <td>{{ product.category }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
<script>
import ApiMixin from "../api.js";

export default {
  name: "",
  mixins: [ApiMixin],
  components: {},
  data() {
    return {
      productList: [],
    };
  },
  setup() {},
  created() {},
  mounted() {},
  unmounted() {},
  methods: {
    async getProductList() {
      this.productList = await this.$callAPI(
        "https://cfa2c3ca-22ae-413f-ba6f-df81768325db.mock.pstmn.io/productList",
        "get",
        {}
      );
      console.log(this.productList);
    },
  },
};
</script>
  • $를 사용해서 믹스인을 만들게 되면 충돌나지 않게끔 구분해준다.
  • 또한 믹스인 마운트 먼저 실행되고 믹스인을 사용하는 컴포넌트 실행됨

monitoring.js

export default {
  mounted() {
    //데이터베이스 시간 저장
  },
  unmounted() {
    //데이터베이스 시간 저장
  },
};

라이프사이클을 통해 사용자의 사이트 이용시간을 알고 싶은 경우 mounted, unmounted를 사용하여 알 수 있다.

mixin.js

import axios from "axios";

export default {
  methods: {
    async $api(url, method, data) {
      //url, 호출하는 방식, 서버로 던질 데이터
      return await axios({
        method: method,
        url: url,
        data: data,
      }).catch((e) => {
        console.log(e);
      }).data;
    },
  },
};

main.js

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import mixins from "./mixins.js";

const app = createApp(App);
app.mixin(mixins);
createApp(App).use(router).mount("#app");

믹스인은 global로도 만들어서 사용할 수 도 있다.

profile
프론트엔드 개발자

0개의 댓글