-
[vue-router] 없는 url 접근 방지, 빈 화면[프로그래밍 | 개발]/[vue] 2021. 8. 26. 16:18
vue 3
vue-router 4
기본적으로 많이들 쓰는 방법이
route 만들 때
{ path: '/:catchAll(.*)', name: 'notFound', component: ErrorPage }이와 같은 방법을 많이 쓰는데, 이렇게 하면
{ path: '/snack', component: LayoutComponent, children: [ { path: 'eat', name: 'eatSnack', component: EatSnack } ] }이런 식으로 칠드런 패스가 정의 되어 있을 때
'www.mainDmain.com/snack'
이런 식으로 children은 있지만 하위'/' 에 대한 컴포넌트가 정의되지 않은 url 은 빈 화면이 뜬다
이 때 router의 beforeEach를 써서 해결한다.
import { createRouter, createWebHistory } from 'vue-router'; import routes from '라우트 정의한 위치'; const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes, }); router.beforEach((to, from, next) => { if (to.name === 'notFound' || to.name === undefined) { // 미리 라우트에 등록한 에러페이지 return next({ name: 'error' }); } ...... return next(); })참고로 최상위 라우트 단위에서 해당 path가 없으면 notFound가 뜨고,
칠드런 단위에서 해당 path 가 없으면 undefined가 뜬다.
'[프로그래밍 | 개발] > [vue]' 카테고리의 다른 글
vue title 새로고침시 변경될 때, 시간차 (0) 2021.08.06