Vuejs 기본 - axios, router

홍예진·2022년 11월 11일
0

Vue.js

목록 보기
6/7

Axios

axios.get(URL) => Promise 객체 return => then, catch 사용 가능
Vue에서 권고하는 Promise 기반 HTTP 통신 라이브러리로 문서화가 잘 되어있고 API가 다양합니다.

Promise

  • 서버에 데이터를 요청하여 받아오는 동작과 같은 비동기 로직 처리에 유용한 자바스크립트 라이브러리
  • JS는 단일 스레드로 코드를 처리하기 때문에 특정 로직의 처리가 끝날 때까지 기다려주지 않기 때문에, 기다렸다 화면에 나타나는 로직을 실행할 때 주로 Promise객체를 사용

axios 설치

CDN

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"><

NPM

npm install axios

axios API

axios('url'); // default : get
axios.get('url').then().catch(); // get요청
axios.post('url').then().catch(); // post요청
axios.put('url').then().catch(); // post요청
axios.delete('url').then().catch(); // post요청

// axios({옵션 속성(config)})
axios({
	method: 'post',
	url: '/user',
  	data: {
    	name: '홍길동',
      	userid: 'hong123'
    }
});

axios({
	method : 'get'
  	url : '/user/velog'
  	responseType : 'json'
})
.then(function(response){
	// logic
});

vue-router

요지는 지정한 vue에 component를 갖다 붙여 연결하는 것!

CDN

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router@3.5.3/dist/vue-router.js"></script>

NPM

npm install vue-router

vue-router 이동 및 렌더링

  • 네비게이션을 위해 router-link 컴포넌트를 사용(기본적으로 <a>태그로 렌더링됩니다.)
  • 속성은 to prop을 사용

router-view

  • 현재 라우트에 맞는 컴포넌트가 렌더링됩니다.
const router = new VueRouter({
	routs : [
    ...,
    {
    	path: '/board',
        name: 'board',
        component : Board,
    },
    {
    	path: '/board/:no',
        name: 'boardView',
        component : BoardView,
    },
    ...
    ],
});
// 연결 예시 /boardview
<router-link :to="{name: 'boardview', params: {no: 3}}">3번 게시글</router-link>
<a @click="$router.push({name:'boardview', params: {no: 3}});">3번 게시글</a>

// 쿼리스트링으로 넘길 수도 있다. 이때 url = /boardview?no=3
<router-link :to="{name: 'boardview', query: {no: 3}}">3번 게시글</router-link>

중첩된 라우트

  • 앱 UI는 일반적으로 중첩된 구조
{
  path: "/board",
  name: "board",
  component: () => import("@/views/AppBoard.vue"),
  redirect: "/board/list",
  children: [
    {
      path: "list",
      name: "boardlist",
      component: () => import("@/components/board/BoardList"),
    },
    {
      path: "write",
      name: "boardwrite",
      component: () => import("@/components/board/BoardWrite"),
    },
    {
      path: "view/:articleno",
      name: "boardview",
      component: () => import("@/components/board/BoardView"),
    },
    {
      path: "modify/:articleno",
      name: "boardmodify",
      component: () => import("@/components/board/BoardModify"),
    },
    {
      path: "delete/:articleno",
      name: "boarddelete",
      component: () => import("@/components/board/BoardDelete"),
    },
    ...
  ],
},

추가 참고할만한 글

Fetch vs Axios

  • (요약) Axios는 기본적으로 JSON타입. .catch()를 사용하여 에러처리 가능.
profile
기록용 공부용 개발 블로그

0개의 댓글