라우트 컴포넌트에 Props 전달하기
이전에 route를 통해 props를 꺼내는 방법을 사용했습니다. 아래처럼 말이죠.
<!-- User.vue -->
<template>
<div>
User {{ $route.params.id }}
</div>
</template>
import User from './User.vue'
cosnt router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/user/:id',
component: User,
},
],
})
하지만, User.vue에서 $route
에 대한 직접적인 의존성을 제거하기 위해 props
를 선언할 수 있습니다.
<script setup>
defineProps({
id: String
})
</script>
<template>
<div>
User {{ id }}
<div>
</template>
<script>
export default {
props: {
id: String
}
}
</script>
<template>
<div>
User {{ id }}
</div>
</template>
위에처럼 $route
or useRoute()
를 사용하여 params
를 통해 데이터를 꺼내지 않고 props
로 데이터를 꺼낼 때는 아래와 같이 props
속성 값을 선언해 줍니다.
const routes = [
{ path: '/user/:id', component: User, props: true }
]
Named View props
이름이 있는 뷰가 있는 라우트의 경우, 이름이 있는 뷰 각각에 설정을 해주어야 합니다.
cosnt routes = [
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false },
},
]
Object Props Mode
props
가 객체인 경우, 이는 그대로 컴포넌트의 props
로 설정되게 됩니다.props
가 정적일 때 유용합니다.
이때, :param
을 이용한 props전달은 할 수 없습니다.
const routes = [
{
path: '/promotion/from-newsletter',
component: Promotion,
props: {
routeObject: {
a: 0,
b: 'test',
c: true,
},
dummy: false,
},
},
]
위와 같이 작성되어 있다면 아래와 같이 사용 할 수 있습니다.
<script setup>
const props = defineProps(['routeObject', 'dummy'])
</script>
<template>
<h1>{{ props.dummy }}</h1> <!-- false -->
<div>
<span>{{ props.routeObject.a }}</span> <!-- 0 -->
<span>{{ props.routeObject.b }}</span> <!-- test -->
<span>{{ props.routeObject.c }}</span> <!-- true -->
</div>
</template>
Function Mode
props
를 반환하는 함수를 만들 수도 있습니다.
이를 통해 데이터 타입을 캐스팅한다던가, 정적 값을 라우트 기반( route.params
or route.query
)의 값과 결합하는 등의 작업을 수행할 수 있습니다.
<router-link :to="{ name: 'router2', query: { test: '사과돌려깍기' } }">라우터 공부하러 가자 함수 모드</router-link>
cosnt routes = [
{
path: '/router2',
name: 'router2',
props: (route) => ({ functionData: route.query.test }),
component: () => import('@/components/RouterStudy.vue'),
}
]
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
const props = defineProps(['routeObject', 'route', 'functionData']);
console.log(route.params);
console.log(props.routeObject);
console.log(props.route);
console.log(props.functionData);
</script>
위의 결과값은 다음과 같이 나오게 될것입니다.
{}
undefined
undefined
사과돌려깍기
참고사항
RouterView에서 직접....
<router-view>
의 슬록을 통해 props
를 전달할 수 있습니다.
하지만, 이 방법은 모든 view컴포넌트가 view-prop을 전달받게 됩니다.
좋은 방법은 아니지요.. 꼭 필요한 경우가 아니라면 위에 방법중 하나를 사용합시다.
<RouterView v-slot="{ Component }">
<component
:is="Component"
view-prop="value"
/>
</RouterView>
728x90
반응형
'FrameWorks > Vue' 카테고리의 다른 글
VueRouter의 Diffrenet History Modes 파헤치기 (0) | 2024.06.26 |
---|---|
VueRouter의 Active Links 파헤치기 (0) | 2024.06.23 |
VueRouter의 Redirection & Alias 파헤치기 (0) | 2024.06.23 |
VueRouter의 Named View 파헤치기 (0) | 2024.06.23 |
VueRouter의 Programmatic Navivation 파헤치기 (0) | 2024.06.23 |
댓글