Vue3 Router

router는 ~/경로와 같이 이동 경로를 설정할 수 있는 라우팅을 지원한다. 라우터를 사용하기 위해 router.js, main.js, App.vue 3가지 파일을 수정해야 한다. 

 

router.js: 없다면 생성

import { createWebHistory, createRouter } from "vue-router";
import Home from './components/HelloWorld.vue'
import SampleComp from './components/SampleComp.vue'

const routes = [
    {
      path: "/",
      name: "home",
      component: Home,
    },
    {
      path: "/sample",
      name: "sample",
      component: SampleComp,
    },
  ];
  
  const router = createRouter({
    history: createWebHistory(),
    routes,
  });
  
  export default router;

이동 경로와 보여질 컴포넌트 등 세부적인 내용을 {path, name, component} 형태로 작성한다. name은 라우터로 연결할 때 사용되는 이름인데 생략 가능하다. 

 

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from "./router.js"

const app = createApp(App)
app.use(router).mount('#app')

main.js에 설정한 라우터를 등록해준다.

 

App.vue

<template>
  <div>
    <router-link to="/">Home</router-link>
    <router-link to="/sample">Sample</router-link>
  </div>
  <router-view></router-view>
</template>
  • router-link: to를 통해 이동할 경로를 설정해준다. <a> 태그와 같이 클릭하면 해당 경로의 컴포넌트가 나타난다. 
  • router-view: 현재 경로에 할당된 컴포넌트가 나타나는 위치이다. 

동적 라우팅

const routes = [
    {
        path: "/:id/:name",
        component: SampleComp
    }
];

만약 "/:이름"과 같이 경로를 설정한다면 접근한 주소를 사용해 컴포넌트를 처리할 수 있다. 

<template>
  <div>[ {{$route.params.id}}: '{{$route.params.name}}' ]</div>
</template>

{{$route.params.이름}}을 통해 주소 자체를 사용한다. 예를 들어 ~/3/David로 접근했다면 화면에 [ 3: 'Daivd' ]가 나타나다. 만약 쿼리가 포함되어 있다면 {{$route.query}}와 같이 사용할 수도 있다. 


redirection - 404 Not Found

사용자가 특정 주소로 들어왔을 때, redirection하는 작업도 router로 처리한다. 대표적인 상황이 404 페이지로 redirection하는 경우다. 

{
  path: "/404",
  name: "notFoundView",
  component: NotFoundView,
},
{
  path: "/:pathMatch(.*)*",
  redirect: "/404",
},

/404 페이지를 설정하고, 위에서 설정한 경로와 일치하지 않는 모든 경로를 /404로 보낸다. 이렇게 하면 예상치 못한 경로로 접근한 사용자에게 404 페이지를 보여줄 수 있다.