이번 포스트에서는 작지만 유용한 라우팅 기법들에 대해 살펴보자.
reidrect와 alias
redirect
redirect는 어떤 경로로 요청이 들어왔을 때 다른 경로로 연결하는 기법을 의미한다. 예를 들어 링크 설계는 이미 되었지만 아직 컴포넌트 구현은 되지 않은 경우 404로 처리하는 대신 EmptyComponent로 redirect를 요청할 수 있다.
{
path:"/etc/nextstep1",
redirect: "/under"
},
{
path:"/etc/nextstep2",
redirect: {name:'underconstruction'}
}
redirect 할 때에는 일반적으로 redirect 된 route의 component를 사용하면 되기 때문에 component 속성이 불필요하다. redirect를 하면 새로운 경로로 이동하는 것이기 때문에 URL이 변경된다.
alias
alias 즉 별칭은 하나의 route에 alias를 추가하여 여러 이름으로 호출하는 것을 말한다.
{
path:"/etc/alias1",
component: AliasView,
alias:"/etc/alias2"
},
경로 component에 props 전달하기
route의 params를 props로
dynamic route에서 전달되는 params를 사용하려면 useRoute()를 통해서 route 객채를 가져와서 사용해야 하는 번거로움이 있다. 이때 props 옵션을 사용하면 바로 props에서 확인할 수 있어서 편리하다. 즉 router의 params를 props로 변환해주는 것이다.
예를 들어 id라는 params를 써야한다고 했을 때 props를 사용하면 상황에 따라 훨씬 코드 절감 효과가 있다.
// 최소 두줄 필요~
import { useRoute } from 'vue-router';
const route = useRoute();
// 한줄이면 끝! 원래 다른 props도 있었다면 그냥 사용 가능
const props = defineProps(["id"]);
그럼 어떻게 하면 이런 처리가 가능한가? 그냥 간단히 router를 설정할 때 props 속성을 넣어주면 된다.
{
path:'/etc/useprops1/:id',
component:UsePropsView,
props: true
}
추가로 단순한 prop을 전달할 계획이라면 route에 props로 전달할 수도 있다.
{
path: '/etc/useprops2/static',
component: UsePropsView,
props: { id: '이건 그냥 props로 만든것' }
}
다양한 history mode
history mode
router를 작성할 때는 이동이 발생할 때 URL의 형태를 설정할 수 있는데 html5 mode와 hash mode가 사용된다. 이 설정은 createRouter를 통해 router를 생성할 때 history 속성을 이용해서 처리한다.
history의 속성의 값으로 hash mode를 사용하려면 createWebHashHistory()를 사용하고 html5 mode를 사용하려면 createWebHistory()를 사용한다.
const router = createRouter({
//history: createWebHistory(import.meta.env.BASE_URL),
history: createWebHashHistory(),
routes:[. . .]
});
createWebHistory는 base url을 파라미터로 받을 수 있는데 import.meta.env는 Vite의 환경변수에 접근하기 위한 property로 기본 BASE_URL은 '/'이다.
다음은 각 모드를 사용했을 때 URL의 형태이다. hash mode는 # 기호를 사용하는 방식이고 html5는 일반적인 웹의 url 형태이다. html5가 좀 더 권장된다.
http://localhost:5173/ http://localhost:5173/sub1 http://localhost:5173/sub2 |
http://localhost:5173/#/ http://localhost:5173/#/sub1 http://localhost:5173/#/sub2 |