본문 바로가기
IT/VueJS

fake api server 사용 예제

by 골든크랩 2022. 8. 24.
728x90
반응형

 

 서버를 개발하지 않고 테스트 할 수 있음.

 

https://jsonplaceholder.typicode.com/

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. As of Oct 2021, serving ~1.7 billion requests each month.

jsonplaceholder.typicode.com

 

하단의 Resources로 내려가서 클릭해보면...데이터를 볼 수 있다.

 

통신을 위해서 Http Client는 Axios 를 사용

https://github.com/axios/axios

 

GitHub - axios/axios: Promise based HTTP client for the browser and node.js

Promise based HTTP client for the browser and node.js - GitHub - axios/axios: Promise based HTTP client for the browser and node.js

github.com

설치 

- npm install axios (npm i axios) 또는 아래

- yarn add axios

 

설치가 되면 package.json파일의 dependencies에 추가됨

 

======================================================

<template>
  <h1>Hello world</h1>
  <hr/>
  <h2>{{ title }}</h2>
  <ul>
    <li v-for="todo in todos" :key="todo.id">
      <a href='#' @click="linkClicked(todo.title)">
        {{todo.title}} :작업완료여부({{ todo.comleted }})
      </a>
    </li>
    <div>
      <!-- 재고총가격 {{calcTotalPrice}} -->
    </div>
  </ul>
    <button @click="buttonClicked">상품추가</button>
 
</template>

<script>
import axios from 'axios';

export default {
  name: 'App',
  computed: {    
  },
  // beforeCreate() {
  //   alert('before create');
  // },
   created(){    
    // 아래 주석을 풀면 에러가 난다. 원인을 이해해야 한다.buttonClicked() 부분이 정확한것이다.
    // 화살표 함수를 사용해야 하는 이유를 고민해봐라.
    //  alert('created');
    //   .then( function(res) {
    //     // console.log(res.data);
    //     this.todos = res.data;
    //   })
    //   .catch(function (err) {
    //     console.log(err);
    //   });
   },
  // beforeMount() {
  //   alert('beforeMountd')
  // },
  // mounted() {
  //   alert('mounted');
  // },
  methods: {
    buttonClicked() {
      console.log('button clicked....');
      .then( res => { //반드시 화살표 함수를 써야 한다.  위의 created() 함수처럼 쓰면 에러난다.
        // console.log(res.data);
        this.todos = res.data;
      })
      .catch( err => {
        console.log(err);
      });
    },
    linkClicked(prod) {
      console.log(`${prod} 이 선택되었습니다.`);
    }

  },
  data() {
    return {
      title: '할일목록',
      todos: [],
    }
  },
  components: {    
  }
}
</script>

<style>
</style>
728x90
반응형

'IT > VueJS' 카테고리의 다른 글

자식 컴포넌트로 데이터 보내기  (0) 2022.08.25
Component 로 만들어 사용하기  (0) 2022.08.25
Computed 메서드 예제  (0) 2022.08.24
첫번째 프로젝트  (0) 2022.08.24
데이터 바인딩, Interpolation  (0) 2022.08.23

댓글