Vue router

임재희·2021년 10월 4일
0

vue

목록 보기
1/1
post-thumbnail

1. router란?

  • router는 페이지를 전환할 때 사용하는 뷰 공식 라이브러리입니다.
  • 뷰는 싱글페이지 어플리케이션(SPA) 방식을 사용합니다.
  • 뷰 외에 리액트, 앵귤러도 라우팅 형식을 사용하고 있습니다.
  • 새로고침이 발생하지 않아 화면 깜빡임 없이 빠른 화면 이동이 가능하다.

SPA란?
기존 웹 서비스는 요청시마다 서버로부터 리소스들과 데이터를 해석하고 화면에 렌더링하는 방식이다. SPA형태는 브라우저에 최초에 한번 페이지 전체를 로드하고, 이후부터는 특정 부분만 Ajax를 통해 데이터를 바인딩하는 방식이다.

📍 yarn 또는 npm을 이용하여 설치

$ yarn add vue-router 
// OR 
$ npm install vue-router --save

2. 사용법

폴더 구조는 이렇습니다.

├── src   
|    ├── pages
|    |    ├── MainPage.vue
|    |    ├── AboutPage.vue
|    |    └── index.js
|    ├── App.vue
|    └── main.js

각 파일을 만들고 아래와 같이 넣어줍니다.

📌 index.js

//export { default as 컴포넌트 이름 } from '루트'; 
export { default as MainPage } from './MainPage'; 
export { default as AboutPage } from './AboutPage'; 

📌 main.js

import Vue from 'vue'
import App from './App.vue'
//router 라이브러리
import VueRouter from 'vue-router';

Vue.config.productionTip = false

// router 기능 확장 선언
Vue.use(VueRouter); 

//index.js에서 컴포넌트 가져오기
import {MainPage, AboutPage} from './page'

//router 등록공간
const routes = [
   {
      path: '/', //경로 설정
      component: MainPage //컴포넌트 이름
   },
   {
      path: '/about',
      component: AboutPage
   }
];

// router 객체생성
const router = new VueRouter({
  routes
});

new Vue({
  render: h => h(App),
  router // router 추가
}).$mount('#app')

📌 App.vue

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>
*router-view : 페이지 표시 태그, 변경되는 url에 대한 해당 컴포넌트를 뿌려준다.

3. 페이지 이동

📖 router-link 사용하기

<template>
    <div>
        <router-link to='/about'>ABOUT</router-link>
    </div>
</template>

📖 button에 router 걸기

<template>
	<button @click="Research()"></button>
</template>

<script>

export default {
	methods: {
    		Research() {
            	     this.$router.push('/about');
                }
        },
    
    }

}
</script>

📖 딜레이 링크

<script>

export default {
	methods: {
    		Research() {
                    setTimeout(() => {
                        this.$router.push({path: '/about'});
                    },1500)
                }
        },
    
    }

}
</script>

4. router event

💡 $router.push

template 내에서 <router-link :to=”path”> 를 통해 페이지 이동을 하면 이는 내부에서 $router.push 를 호출하는 것입니다. push 메소드를 사용하면 히스토리 스택에 추가 됩니다. 아래와 같은 순서로 페이지를 push 하면 스택에 home > product ('P0001') > product ('P0002') 순으로 쌓이게 되고, 뒤로가기 버튼을 눌렀을때 순차적으로 스택에 쌓였던 전 페이지가 보이게 됩니다.


💡 $router.replace

$router.replace 는 push 와 같이 URL 이동을 시키지만 히스토리 스택을 쌓지 않습니다.
단순히 현재 페이지를 전환하는 역할을 하기 때문입니다.


💡 $router.go

$router.go 는 인자로 넘긴 숫자만큼 히스토리 스택에서 앞, 뒤 페이지로 이동하는 메소드 입니다.
음수일 경우 이전페이지, 양수일 경우 다음 페이지를 보여줍니다. 해당 숫자의 URL 이 스택에 없으면 라우팅에 실패하게 됩니다.

this.$router.go(-1) // 한 단계 뒤로
this.$router.go(2) // 두 단계 앞으로

5. 데이터 전달하기

📌 두가지 방법으로 전달합니다.

  • query
this.$router.push({name: 'about', query: {index: this.index, list: this.list}})
  • params
this.$router.push({name: 'about', params: {index: this.index, list: this.list}})

📌 main.js

//router 등록공간
const routes = [
   {
      path: '/',
      component: MainPage
   },
   {
      path: '/about',
      component: AboutPage,
      name: 'about' //데이터를 받을 페이지의 이름을 따로 등록해줍니다.
   }
];

📌 받기

<template>
  <div>
    <p>{{ $route.query.index }}</p>
    <p>{{ $route.params.index }}</p>
  </div>
</template>
profile
하루하루는 성실하게 인생 전체는 되는대로✏️

0개의 댓글