간단한 라우팅 헤더를 만드는 예제입니다.
Vue CLI를 이용해서 프로젝트를 생성한 기준입니다.
만약 프로젝트를 생성하지 않았다면
vue create 프로젝트이름
으로 생성하시기 바랍니다.
npm i vue-router --save
터미널에 입력하여 설치한다.
src
폴더 안에 router
라는 폴더를 만들고, 그 안에 index.js
를 만든다.
마찬가지로 src
폴더 안에 views
라는 폴더를 만들고, 그 안에 페이지에 해당하는 원하는.vue
파일을 만든다.
src/main.js
import Vue from "vue";
import App from "./App.vue";
import { router } from "./router/index.js"; //여기 추가!
Vue.config.productionTip = false;
new Vue({
render: (h) => h(App),
router, //여기 추가!
}).$mount("#app");
src/router/index.js
(만약 vscode의 vetur
를 사용하고 있다면 vrouter
입력 후 tab을 누르면 쉽게 기본 세팅이 된다.
import Vue from "vue";
import VueRouter from "vue-router";
import NewsView from "../views/NewsView.vue";
import AskView from "../views/AskView.vue";
import JobsView from "../views/JobsView.vue";
Vue.use(VueRouter);
export const router = new VueRouter({
mode: "history", //mode를 설정하지 않으면 주소 뒤에 #이 붙는다.
routes: [
{
path: "/", //홈
redirect: "/news", //홈을 /news로 리다이렉팅
},
{
//path: url 주소
path: "/news",
// component: url주소로 갔을 때 표시될 컴포넌트
component: NewsView,
},
{
path: "/ask",
component: AskView,
},
{
path: "/jobs",
component: JobsView,
},
],
});
src
폴더 안에 components
라는 폴더안에 ToolBar.vue
를 만든다.
src/components/ToolBar.vue
<template>
<div class="header">
<router-link to="/news">News</router-link> |
<router-link to="/ask">Ask</router-link> |
<router-link to="/jobs">Jobs</router-link>
</div>
</template>
<style scoped>
.header {
}
.header .router-link-exact-active {
/* 선택된 라우터 */
}
.header a {
/* 나머지 라우터 */
}
</style>
src/App.vue
<template>
<div id="app">
<tool-bar></tool-bar> //import 할때 파스칼케이스로 작성하면 vscode에서 다음과 같이 스네이크 케이스로 자동완성 해준다.
<router-view /> //이 영역이 라우팅 되는것이다.
</div>
</template>
<script>
import ToolBar from "./components/ToolBar.vue";
export default {
components: {
ToolBar, //등록 후 사용. es6의 enhanced object literal 덕분에 원래는 Toolbar : Toolbar로 작성해야 되지만 다음과 같이 작성해도 된다.
},
};
</script>