Post

[Vue] vue-router 상세페이지 /:id, URL파라미터

[Vue] vue-router 상세페이지 /:id, URL파라미터

/detail/:id

/detail/:작명 로 접속하면 작명번 게시물 보여주기
/detail/0 이런식으로 접속하면 detail 페이지가 보여진다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(router.js)

import { createWebHistory, createRouter } from "vue-router";
import compDetail from './components/compDetail.vue';
const routes = [
  {
    path: "/detail/:id",			// :id
    component: compDetail,
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

$route.params.파라미터명

URL 파라미터를 꺼내 쓰고 싶으면 $route.params.id 문법을 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// src/components/compDetail.vue

<template>
  <div class="detail_ttl">
    <h2>{{ blogList[num].title }}</h2>
    <p>{{ blogList[num].date }}</p>
  </div>
  <div class="detail_content">
    {{ blogList[num].content }}
  </div>
  <div class="detail_foot">
    <router-link to="/list">글목록</router-link>
  </div>
</template>

<script>
export default {
  name: 'compList',
  data(){
    return {
      num: this.$route.params.id,
    }
  },
  props: {
    blogList: Array
  }
}
</script>

<style>
.detail_ttl{text-align:center; padding:3rem 2rem;}
.detail_ttl h2{font-weight:700;}
.detail_ttl p{margin:1rem 0 0;}
.detail_content{border-top:1px solid #eee; padding:2rem;}
</style>

파라미터 문법 몇개 더

파라미터 자리에 정규식을 입력할 수 있다.

1
2
3
4
5
6
7
8
9
{
  path: "/detail/:id(\\d+)",	// 숫자만
  component: compDetail,
},
{
  path: "/detail/:id*",	// *을 붙이면 아래와 같은 뜻이다
  path: "/detail/:id/:id/:id/:id/:id..",
  component: compDetail,
}

v-bind:href=”./detail/${a.number}”

링크는?

1
2
( src/components/compList.vue )
<a v-bind:href="`./detail/${a.number}`">
This post is licensed under CC BY 4.0 by the author.