본문 바로가기
Vue.js

#3. Vue.js - Routing(페이지이동), Axios(API 비동기 통신)

by Ristonia 2023. 8. 8.

1.Router

1-1 라우팅이란

단일 페이지 어플리케이션 SPA에서 가장 먼저 처리해야 하는것이 바로 라우팅이다.

페이지를 이동할  서버에 요청하여 새로 페이지를 개인하는것이 아니라, 미리 해당 페이지를 받아놓고 페이지를 이동시 클라이언트의 라우팅을 이용하여 화면을 갱신하는 것으로

이러한 방식을 SPA(Single Page Application)이라고 한다.

라우팅을 사용하여 화면간 전환을 매끄럽게 전환하여 사용자 경험을 향상시킬  있다.

1-2. VueRoute

1.Router

1-1 라우팅이란

단일 페이지 어플리케이션 SPA에서 가장 먼저 처리해야 하는것이 바로 라우팅이다.

페이지를 이동할  서버에 요청하여 새로 페이지를 개인하는것이 아니라, 미리 해당 페이지를 받아놓고 페이지를 이동시 클라이언트의 라우팅을 이용하여 화면을 갱신하는 것으로

이러한 방식을 SPA(Single Page Application)이라고 한다.

라우팅을 사용하여 화면간 전환을 매끄럽게 전환하여 사용자 경험을 향상시킬  있다.

1-2. VueRouter

뷰에서는 뷰라우터(VueRouter)라는 공식라이브러리를 통해 라우터기능을 지원한다.

*cdn 방식으로 사용할때는 ,  라우터 순서로 기술하여 사용해야한다.

 

 라우터는 페이지이동 기능을 제공하여  라우터를 이용하여 뷰로 만든 페이지 간에 자유롭게 이동할  있다.

태그 설명
<router-link to="URL"> 페이지 이동 태그. 화면에서는 <a> 로 표시되며 클릭하면 to에 지정된 URL로 이동한다.
<router-view> 페이지 표시 태그. 변경되는 URL에 따라 해당 컴포넌트를 뿌려주는 영역이다.

 

1-3. VueRouter 등록  

//라우터 인스턴스 생성
var router = new VueRouter({
   //라우터 옵션 기술
   routes : [   //라우팅  URL 컴포넌트  지정 (페이지정보)
        { path : '/login' , component : LoginComponent },
        { path : '/logout' , component : LogoutComponent }
   ], 
   mode : 'history' // URL 해쉬  제거 속성 (URL #해쉬  제거)
})
 
// 인스턴스에 라우터 등록
new Vue({
  router : router
})

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <div>
      <router-link to="/login">Login</router-link>
      <router-link to="/main">Main</router-link>
    </div>
    <router-view></router-view>
  </div>
 
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  <script>
    var LoginComponent = {
      template: '<div>login</div>'
    }
    var MainComponent = {
      template: '<div>main</div>'
    }
 
    var router = new VueRouter({
      // 페이지의 라우팅 정보     
      routes: [
        // 로그인 페이지 정보
        {
          // 페이지의 url
          path: '/login',
          // name: 'login',
          // 해당 url에서 표시될 컴포넌트
          component: LoginComponent
        },
        // 메인 페이지 정보
        {
          path: '/main',
          component: MainComponent
        }
      ]
    });
 
    new Vue({
      el: '#app',
      router: router,
    });
  </script>
</body>
</html>

2. axios - HTTP 통신 라이브러리

2-1. axios

뷰에서 권고하는 HTTP 통신 라이브러리에는 액시오스(Axios) 있다.

이전에는 vue에서 HTTP 통신을 위해 vue resource 라는 공식 라이브러리가 있었으나 현재는 사용하지 않고 있다. (vue-resource.js 참고하는 예제소스에 주의하자.)

 

2-2. axios 기능

브라우저환경 XMLHttpRequests 요청생성

요청/응답 차단(Intercept)

요청/응답 데이터 변환

JSON 데이터 자동 변환.. 

 

2-3. axios 문법

라이브러리를 설치하고 나면 axios라는 변수에 접근할  있게 되며

axios 변수를 사용하여 HTTP 통신의 코드를 작성할  있게된다.

기능 설명 문법
GET 불러오기 서버로부터 데이터를 가져오는데 사용 axios.get
POST 입력하기 서버로 데이터를  저장하는 사용 axios.post
PATCH 수정하기 서버로 데이터를 수정하기 위해 사용 axios.patch
DELETE 삭제하기 서버ㅓ 데이터를 삭제하기 위해 사용 axios.delete

axios Promis 기반의 자바스크립트 비동기 처리방식을 사용하여 요청 , .then()으로 결과값을 받아서 처리를 하는 형식으로 구성되어 있다.

axios.get('/api/data').then(res => {
 console.log(res.data)
})

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Axios</title>
</head>
<body>
  <div id="app">
    <button v-on:click="getData">get user</button>
    <div>
      {{ users }}
    </div>
  </div>
 
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: {
        users: []
      },
      methods: {
        getData: function() {
          var vm = this;
          axios.get('https://jsonplaceholder.typicode.com/users/') //사용자정보 배열 테스트데이터
            .then(function(response) { //then 응답성공
              console.log(response.data);
              vm.users = response.data;
             // this.users = response.data; //axios.get 호출전,후의 this 다름
                                            //호출하기전의 this 기본적인 인스턴스, 컴포넌트를 바라보는 this
                                            //then() 호출후의 this 비동기처리  실행컨텍스트가 바뀐 this
            })
            .catch(function(error) { //catch 응답실패
              console.log(error);
            });
        }
      }
    })
  </script>
</body>
</html>

 

구성(configuration) 설정을 axios() 전달하여 요청할  있다.

axios({
 method : 'post',
 url : '',
 data : {
   usernm : ''
 }
}).then(function(response){
    console.log(response);
});
 
//별칭메소드 사용시
axios.put('/usr/12345',{
  userNm : ''
})

 

2-4. Async 문법

async/await  사용할경우 함수 또는 메서드 앞에 async 키워드를 사용한다.

내부에 async 키워드를 사용해 비동기 통신 요청을 처리하며 async/await  오류 디버깅을 위해 try..catch  사용할  있다.

async/await는 ES8  추가된 새로운 방법으로 IE  포함한 오래된 브라우저는 지원하지 않는다고 한다.

 

2-5. 글로벌 axios 기본 (default)설정

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
 

r

뷰에서는 뷰라우터(VueRouter)라는 공식라이브러리를 통해 라우터기능을 지원한다.

*cdn 방식으로 사용할때는 ,  라우터 순서로 기술하여 사용해야한다.

 

 라우터는 페이지이동 기능을 제공하여  라우터를 이용하여 뷰로 만든 페이지 간에 자유롭게 이동할  있다.

태그 설명
<router-link to="URL"> 페이지 이동 태그. 화면에서는 <a> 로 표시되며 클릭하면 to에 지정된 URL로 이동한다.
<router-view> 페이지 표시 태그. 변경되는 URL에 따라 해당 컴포넌트를 뿌려주는 영역이다.

 

1-3. VueRouter 등록  

//라우터 인스턴스 생성
var router = new VueRouter({
   //라우터 옵션 기술
   routes : [   //라우팅  URL 컴포넌트  지정 (페이지정보)
        { path : '/login' , component : LoginComponent },
        { path : '/logout' , component : LogoutComponent }
   ], 
   mode : 'history' // URL 해쉬  제거 속성 (URL #해쉬  제거)
})
 
// 인스턴스에 라우터 등록
new Vue({
  router : router
})

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <div>
      <router-link to="/login">Login</router-link>
      <router-link to="/main">Main</router-link>
    </div>
    <router-view></router-view>
  </div>
 
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  <script>
    var LoginComponent = {
      template: '<div>login</div>'
    }
    var MainComponent = {
      template: '<div>main</div>'
    }
 
    var router = new VueRouter({
      // 페이지의 라우팅 정보     
      routes: [
        // 로그인 페이지 정보
        {
          // 페이지의 url
          path: '/login',
          // name: 'login',
          // 해당 url에서 표시될 컴포넌트
          component: LoginComponent
        },
        // 메인 페이지 정보
        {
          path: '/main',
          component: MainComponent
        }
      ]
    });
 
    new Vue({
      el: '#app',
      router: router,
    });
  </script>
</body>
</html>

2. axios - HTTP 통신 라이브러리

2-1. axios

뷰에서 권고하는 HTTP 통신 라이브러리에는 액시오스(Axios) 있다.

이전에는 vue에서 HTTP 통신을 위해 vue resource 라는 공식 라이브러리가 있었으나 현재는 사용하지 않고 있다. (vue-resource.js 참고하는 예제소스에 주의하자.)

 

2-2. axios 기능

브라우저환경 XMLHttpRequests 요청생성

요청/응답 차단(Intercept)

요청/응답 데이터 변환

JSON 데이터 자동 변환.. 

 

2-3. axios 문법

라이브러리를 설치하고 나면 axios라는 변수에 접근할  있게 되며

axios 변수를 사용하여 HTTP 통신의 코드를 작성할  있게된다.

기능 설명 문법
GET 불러오기 서버로부터 데이터를 가져오는데 사용 axios.get
POST 입력하기 서버로 데이터를  저장하는 사용 axios.post
PATCH 수정하기 서버로 데이터를 수정하기 위해 사용 axios.patch
DELETE 삭제하기 서버ㅓ 데이터를 삭제하기 위해 사용 axios.delete

axios Promis 기반의 자바스크립트 비동기 처리방식을 사용하여 요청 , .then()으로 결과값을 받아서 처리를 하는 형식으로 구성되어 있다.

axios.get('/api/data').then(res => {
 console.log(res.data)
})

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Axios</title>
</head>
<body>
  <div id="app">
    <button v-on:click="getData">get user</button>
    <div>
      {{ users }}
    </div>
  </div>
 
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: {
        users: []
      },
      methods: {
        getData: function() {
          var vm = this;
          axios.get('https://jsonplaceholder.typicode.com/users/') //사용자정보 배열 테스트데이터
            .then(function(response) { //then 응답성공
              console.log(response.data);
              vm.users = response.data;
             // this.users = response.data; //axios.get 호출전,후의 this 다름
                                            //호출하기전의 this 기본적인 인스턴스, 컴포넌트를 바라보는 this
                                            //then() 호출후의 this 비동기처리  실행컨텍스트가 바뀐 this
            })
            .catch(function(error) { //catch 응답실패
              console.log(error);
            });
        }
      }
    })
  </script>
</body>
</html>

 

구성(configuration) 설정을 axios() 전달하여 요청할  있다.

axios({
 method : 'post',
 url : '',
 data : {
   usernm : ''
 }
}).then(function(response){
    console.log(response);
});
 
//별칭메소드 사용시
axios.put('/usr/12345',{
  userNm : ''
})

 

2-4. Async 문법

async/await  사용할경우 함수 또는 메서드 앞에 async 키워드를 사용한다.

내부에 async 키워드를 사용해 비동기 통신 요청을 처리하며 async/await  오류 디버깅을 위해 try..catch  사용할  있다.

async/await는 ES8  추가된 새로운 방법으로 IE  포함한 오래된 브라우저는 지원하지 않는다고 한다.

 

2-5. 글로벌 axios 기본 (default)설정

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
 

'Vue.js' 카테고리의 다른 글

#6. Vue.js - Vuex  (0) 2023.08.08
#5. Vue.js - Vue CLI  (0) 2023.08.08
#4. Vue.js - 템플릿 문법, 양방향 데이터바인딩, 데이터변화 감지  (0) 2023.08.08
#2. Vue.js - 컴포넌트 통신규칙  (1) 2023.08.08
#1. Vue.js 란?  (1) 2023.08.08