SPA란?
기존 웹 서비스는 요청시마다 서버로부터 리소스들과 데이터를 해석하고 화면에 렌더링하는 방식이다. SPA형태는 브라우저에 최초에 한번 페이지 전체를 로드하고, 이후부터는 특정 부분만 Ajax를 통해 데이터를 바인딩하는 방식이다.
📍 yarn 또는 npm을 이용하여 설치
$ yarn add vue-router
// OR
$ npm install vue-router --save
폴더 구조는 이렇습니다.
├── 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-link 사용하기
<template>
<div>
<router-link to='/about'>ABOUT</router-link>
</div>
</template>
<a>
태그로 치환된다.📖 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>
💡 $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) // 두 단계 앞으로
📌 두가지 방법으로 전달합니다.
this.$router.push({name: 'about', query: {index: this.index, list: this.list}})
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>