Vue router 설정

sdsdsrd·2020년 11월 10일
0

졸업프로젝트

목록 보기
7/15

1. 뷰 라우터 설치

npm i vue-router

2. main.js

import Vue from 'vue';
import App from './App.vue';
import router from '@/routes/index';

Vue.config.productionTip = false;

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

3. @/routes/index.js 폴더 및 파일 생성

import Vue from 'vue';
import VueRouter from 'vue-router';
...

Vue.use(VueRouter);

const router = new VueRouter({
	mode: 'history',
	routes: [
		{
			path: '/',
			redirect: '/sign-in',
		},
		{
			path: '/sign-in',
			component: () => import('@/views/login/SignInPage.vue'),
		},
          
          ...
        	{
			path: '/history',
			name: 'history',
			component: () => import('@/views/order/HistoryPage.vue'),
			meta: { auth: true },
		},
          
          ],
});

...
router.beforeEach((to, from, next) => {
	if (to.meta.auth && !store.getters.isLogin) {
		console.log('인증이 필요합니다');
		next('/sign-in');
		return;
	}
  
  ...
  
 	 if (from.path == '/cart' && to.path == '/my-menu/detail') {
		next('/my-menu');
		return;
	}
  
  ...
  
  	next();
}

url 주소의 #을 없애준다.

	mode: 'history',

http://localhost:8081/ 에 접속했을 때 http://localhost:8081/sign-in으로 redirect하여 초기 진입 페이지를 설정한다.

	routes: [
		{
			path: '/',
			redirect: '/sign-in',
		},

component를 하나씩 import하지 않고 설정하는 방법

component: () => import('@/views/login/SignInPage.vue'),

인증이 필요한 페이지는 router.beforeEach로 다시 로그인 할 수 있도록 함

import store from '@/store/index';

...

        	{
			path: '/history',
			name: 'history',
			component: () => import('@/views/order/HistoryPage.vue'),
			meta: { auth: true },
		},
          
          ],
});

...
router.beforeEach((to, from, next) => {
	if (to.meta.auth && !store.getters.isLogin) {
		console.log('인증이 필요합니다');
		next('/sign-in');
		return;
	}
  	next();
}

/my-menu/detail 페이지는 앞 페이지인 /my-menu에서 데이터를 가져와야함. /cart페이지에서 /my-menu/detail페이지로 뒤로가기를 경우 처리 필요.

 	 if (from.path == '/cart' && to.path == '/my-menu/detail') {
		next('/my-menu');
		return;
	}

if문 마다

next();
return;

을 처리 해주고 마지막에

next();

를 해줘야 다음 페이지로 잘 넘어간다!

0개의 댓글