How to access parameters of multiple nested routes? #486
-
In a Nuxt 3 application, let's say that I have the following page structure: pages/
└── products/
├── [product_id]/
│ └── versions/
│ └── [version_id].vue
└── [product_id].vue This page structure generates the following routes:
Since the <template>
<div>
<h1>Page content for {{ route.path }}</h1>
<div v-if="route.params.version_id">{{ route.params.version_id }}</div>
<!-- nested page content -->
<NuxtPage />
</div>
</template>
<script setup lang="ts">
const route = useRoute('products-product_id')
</script> In the example above, the Since my app contains these nested routes, the only way to not have a type error within this page component is to "cheat" and change the typed route definition in the parent component to this: const route = useRoute('products-product_id-versions-version_id') By forcing the In my real-world use-case, I have several nested routes, so it's impossible to "cheat" and I will always get some form of error when attempting to conditionally access route parameters of nested routes in a parent page component. Is it possible to tell the Originally, without reading through the documentation, I guessed that I could do something like this (spoiler alert, you cannot): const route = useRoute('products-product_id' | 'products-product_id-versions-version_id') |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Technically, you shouldn't use a param from a deeper view: why should that view be aware of it? Maybe the nested routing wasn't needed and you just wanted to split your page component into multiple ones. You guess right, you can do what you wanted, you just used the or bitwise operator instead of thy TS union one: const route = useRoute('' as 'products-product_id' | 'products-product_id-versions-version_id') This would be a more realistic type that would allow you to write something like: <MyComp v-if="'productId' in route.params'" :productId="route.params.productIt" /> |
Beta Was this translation helpful? Give feedback.
Technically, you shouldn't use a param from a deeper view: why should that view be aware of it? Maybe the nested routing wasn't needed and you just wanted to split your page component into multiple ones.
You guess right, you can do what you wanted, you just used the or bitwise operator instead of thy TS union one:
This would be a more realistic type that would allow you to write something like: