SPA/Vue
vuejs 라우터 설치 및 구현
memeseo
2021. 5. 10. 17:10
1. 라우터 설치
npm i vue-router --save
2. package.json 안에 dependencies에 "vue-router": "^3.5.1" 확인
3. routes 폴더 생성 index 파일 생성
-> index 파일에 vueRouter 등록
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
export const router = new VueRouter ({
mode : 'history', //url # 없애는 코드
routes : [
{
//path : ' '
//component :
}
]
)};
4. main.js에 router 등록
import Vue from 'vue';
import App from './App.vue';
import { router } from './routes/index.js';
Vue.config.productionTip = false;
new Vue({
render : h => h(App),
router
}).$mount('#app')
5. views 폴더 만들어서 만들고자 하는 components 생성
6. routes 폴더 index에 views 폴더의 components 등록
import Vue from 'vue';
import VueRouter from 'vue-router';
import NewsView from '../views/NewsView.vue'
import JobsView from '../views/JobsView.vue'
import AskView from '../views/AskView.vue'
import UserView from '../views/UserView.vue'
import ItemView from '../views/ItemView.vue'
Vue.use(VueRouter);
export const router = new VueRouter ({
mode : 'history', //url # 없애는 코드
routes : [
{
path : '/',
redirect : '/news'
},
{
//path : url주소
path : '/news',
// components : url 주소로 갔을 때 표시될 컴포넌트 / page
component : NewsView
},
{
path : '/ask',
component : AskView
},
{
path : '/jobs',
component : JobsView
},
{
path : '/user',
component : UserView
},
{
path : '/item',
component : ItemView
}
]
});
7. App.vue로 돌아와 라우터 이용해 component들이 잘 불러와 지는지 확인
<template>
<div>
<router-view></router-view>
</div>
</template>
확인 방법
http://localhost:8084/news
배경색 칠해진 부분에 본인이 입력한 path 타이핑