가수면

[Vue] Router 본문

Vue

[Vue] Router

니비앙 2024. 5. 16. 22:35

라우팅

내부 페이지 라우팅

href 속성에 #id(섹션 id) 설정

// Navbar
        <ul class="navbar-nav ms-auto">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="#title">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#portfolio">Portfolio</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#about">About</a>
          </li>
        </ul>
        
        
// Title 섹션
<template>
  <section id="title">
  
  ..
  
// Portfolio 섹션
  <template>
  <section id="portfolio" class="container">
  
  ..
  
// About 섹션
  <template>
  <section id="about" class
  
  ..

페이지 라우팅

npm i vue-router

// router.ts

import { createWebHistory, createRouter } from "vue-router";
import TitlePage from "../components/Title.vue";
import About from "../components/About.vue";
import Portfolio from "../components/Portfolio.vue";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: "/", component: TitlePage },
    { path: "/about", component: About },
    { path: "/portfolio", component: Portfolio },
  ],
});

export default router;
// main.ts

import router from "./router/router.ts";

createApp(App).use(router).mount("#app");
// App.vue

      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav ms-auto">
          <li class="nav-item">
            <router-link class="nav-link active" aria-current="page" to="/">Home</router-link>
          </li>
          <li class="nav-item">
            <router-link class="nav-link" to="/portfolio">Portfolio</router-link>
          </li>
          <li class="nav-item">
            <router-link class="nav-link" to="/about">About</router-link>	// a 태그 역할
          </li>
        </ul>
      </div>
    </div>
  </nav>
  <router-view />	// 라우터로 연결되는 페이지가 이 자리에 표시 됨

다이나믹 라우트

{ path: "/detail/:id", component: Detail }

params 사용

<template>
  <section id="detail" class="container">
    <h1>Detail</h1>
    {{ $route.params.id }}		// 택 1
  </section>
</template>

<script setup lang="ts">
const route = useRoute();
const params = +route.params.id;	// 택 1
</script>

<style></style>

 

'Vue' 카테고리의 다른 글

Vuetify 컴포넌트 자식 요소의 스타일 커스텀하는 방법  (0) 2024.08.26
[Vue] 심화  (0) 2024.05.25
[Vue] 전역 상태 관리  (0) 2024.05.16
[Vue] Composition API 방식  (0) 2024.05.13
[Vue] 기본  (0) 2024.05.13
Comments