프레임워크/Vue

[Vue] Vue-Router (404 처리, URL 파라미터, $router)

은돌1113 2024. 4. 27. 13:50

1️⃣ 404 페이지 처리하는 방법

: path에 사용자 정의 정규식을 사용하여 처리할 수 있습니다.

  • /routes/router.js
    import { createWebHistory, createRouter } from "vue-router";
    
    import Home from "../pages/Home"
    import List from "../pages/List"
    import Error from "../pages/Error"
    
    const routes = [
        {
            path: "/",
            component: Home,
        },
        {
            path: "/list",
            component: List,
        },
        {
            path: "/:catchAll(.*)", // 사용자 정의 정규식을 사용하여 catch-all 라우트 정의
            component: Error
        }
    ];
    
    const router = createRouter({
        history: createWebHistory(),
        routes,
    });
    
    export default router;​
  • main.js
    import { createApp } from 'vue'
    import App from './App.vue'
    
    import router from './routes/router'
    
    createApp(App).use(router).mount('#app')​

 위 코드에 있는 /:catchAll(.*)과 같이 URL 파라미터 뒤에 (정규식)을 넣으면 조건에 부합하는 경우에만 해당 컴포넌트를 노출할 수 있어 엄격하게 관리할 수도 있습니다.


2️⃣ URL 파라미터

  • router.js에서는 URL 파라미터를 설정하고 싶은 route path 뒤에 /:id를 사용하여 :id의 값을 컴포넌트에서 받아올 수 있도록 설정합니다.(: 뒤에 오는 이름은 원하는 대로 설정할 수 있습니다.)
    import { createWebHistory, createRouter } from "vue-router";
    
    import Home from "../pages/Home"
    import List from "../pages/List"
    import Detail from "../pages/Detail"
    import Error from "../pages/Error"
    
    const routes = [
        {
            path: "/",
            component: Home,
        },
        {
            path: "/writing",
            component: List,
        },
        {
            path: "/writing/:id", // URL 파라미터
            component: Detail
        },
        {
            path: "/:catchAll(.*)", // 사용자 정의 정규식을 사용하여 catch-all 라우트 정의
            component: Error
        }
    ];
    
    const router = createRouter({
        history: createWebHistory(),
        routes,
    });
    
    export default router;​
  • URL 파라미터 받아오는 페이지
    <template>
      <h1>상세</h1>
      <p>{{ $route }}
    </template>
    
    <script>
    export default {
      name: "Detail",
      mounted() {
        console.log(this.$route); // script에서 값을 사용할 때는 앞에 this.을 붙여줘야 합니다.
      },
    };
    </script>
    
    <style></style>​​
    console.log(this.$route);

 

 URL 파라미터 외에도 ?test='test'와 같이 query로 전달하는 값도 URL 파라미터와 동일하게 $route에서 확인할 수 있다.


3️⃣ $router

: @click이나 함수 내에서 페이지를 이동하거나, 뒤로 가기 기능을 개발할 때는 $router를 사용할 수 있습니다.

<button @click="$router.push('/')">홈으로</button>
<button @click="$router.back()">뒤로 가기</button>