Vue - 페이지 컴포넌트에 Props 전달

h.Im·2024년 9월 13일
0

Vue 기초

목록 보기
12/28
post-thumbnail

ref로 object 타입을 선언하는 경우와 reactive로 object 타입을 선언하는 경우의 차이점.
ref로 선언하면 새로운 object를 덮어씌워도 반응형을 잃지 않고, reactive로 선언하면 반응형을 잃는다?

ref는 proxy이고, reactive는 아닌 것이야?


페이지 컴포넌트에 props 전달하는 방법

이전에는 부모 컴포넌트에서 자식 컴포넌트에 props를 전달하는 방법을 배웠습니다. 이번에는 페이지 컴포넌트에 props를 전달하는 방법을 배워 보겠습니다.

Boolean 모드

...

const routes = [
  {
    path: '/user/:id',
    component: UserView,
    props: true, // id가 UserView 컴포넌트에 props로 전달됨
  }
];

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

UserVuew에서는 아래와 같이 id라는 props를 선언하여 사용합니다.
이 경우, URL이 /user/123일 때, id는 123으로 전달됩니다.

<!-- UserView.vue -->
<template>
  <div>
    <h1>User ID: {{ id }}</h1>
  </div>
</template>

<script>
export default {
  props: ['id'], // params의 id가 props로 전달됨
};
</script>

객체 모드

props에 객체를 전달하여 정적인 데이터를 컴포넌트에 넘길 수 있습니다.

const routes = [
  {
    path: '/static',
    component: StaticView,
    props: { name: 'John', age: 30 } // 정적인 데이터를 전달
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});
<!-- StaticView.vue -->
<template>
  <div>
    <h1>Name: {{ name }}</h1>
    <h2>Age: {{ age }}</h2>
  </div>
</template>

<script>
export default {
  props: ['name', 'age'],
};
</script>

함수 모드

함수를 사용해 라우터의 params, query, 또는 다른 데이터를 기반으로 동적으로 props를 전달할 수 있습니다.

const routes = [
  {
    path: '/user/:id',
    component: UserView,
    props: (route) => ({ id: route.params.id, search: route.query.q })
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});
<!-- UserView.vue -->
<template>
  <div>
    <h1>User ID: {{ id }}</h1>
    <p>Search Query: {{ search }}</p>
  </div>
</template>

<script>
export default {
  props: ['id', 'search'],
};
</script>

함수의 특성 상, 위 예시와 같은 단순 전달 보다는 아래 예시 코드와 같은 추가 동작을 수행하는 경우가 많을 것으로 보입니다.


동적 데이터 가공

예시) 날짜를 전달할 때, params에서 받은 날짜 문자열을 가공하여 컴포넌트로 전달할 수 있습니다.

const routes = [
  {
    path: '/event/:date',
    component: EventView,
    props: (route) => {
      const formattedDate = new Date(route.params.date).toLocaleDateString();
      return { date: formattedDate };
    }
  }
];

기본 값 설정

예시) 검색 쿼리가 없을 때 기본 검색어를 설정할 수 있습니다.

const routes = [
  {
    path: '/search',
    component: SearchView,
    props: (route) => ({ query: route.query.q || 'default search term' })
  }
];

다른 라우트 정보 사용

예시) 라우트의 fullPath를 컴포넌트로 전달하여 전체 URL을 사용할 수 있습니다.

const routes = [
  {
    path: '/page/:id',
    component: PageView,
    props: (route) => ({ fullUrl: route.fullPath })
  }
];

동적/조건부 라우팅 처리

예시) 사용자 권한에 따라 다르게 처리하는 경우

const routes = [
  {
    path: '/dashboard',
    component: DashboardView,
    props: (route) => {
      const isAdmin = route.query.role === 'admin';
      return { isAdmin };
    }
  }
];

0개의 댓글