gj1
gj1

Reputation: 70

Vue passing props via router-link with dynamic routing

I have the following route:

routes/index.ts

{
  path: "/flower/:id",
  name: "SingleFlower",
  component: () => import("@/components/SingleFlower/SingleFlower.vue"),
  meta: { requiresAuth: true },
  props: true 
},

and components:

FlowersPage.vue

...
<router-link
  v-for="flower in flowersArray"
  :key="flower.id"
  :to="{
    name: 'SingleFlower',
    params: { 
      id: flower.id,
    }, 
    // 👈🏽 I want to pass the rest of the props here, eg. flower.name and flower.desc 
  }"
>
  <FlowerCard :flower="flower" />
</router-link>
...

SingleFlower.vue

<template>
  <div class="flower-container">
    {{ flower.id }} 
    {{ flower.name }} // 👈🏽 Using passed props here
    {{ flower.description }} // 👈🏽 Using passed props here
  </div>
</template>

<script setup lang="ts">
  // 👈🏽 How to get props here from router-link and use them in the template
</script>

<style lang="scss">
@import "./FlowerPage.scss";
</style>

How I can achieve the desired effect, as described by the comments in the code above? I've tried to use params as props (e.g. params: { id: flower.id, name: flower.name, desc: flower.desc}) but that didn't work either. What am I doing wrong?

Upvotes: 0

Views: 985

Answers (1)

yoduh
yoduh

Reputation: 14649

a route with props: true will automatically assign route params to a component's props. You can access the props as you would normally:

<template>
  <div>{{ flower.id }} {{ flower.name }} {{ flower.description }}</div>
</template>
<script setup>
const flower = defineProps(['id', 'name', 'description']);
</script>

The only additional thing you need to do is make sure all the params are part of your URL. If the param isn't in the URL, it won't be included as a param and it won't be assigned to a prop:

{
  path: "/flower/:id/:name/:description",
  name: "SingleFlower",
  component: () => import("@/components/SingleFlower/SingleFlower.vue"),
  meta: { requiresAuth: true },
  props: true 
},

If a URL like that is not desirable, I would suggest combining vue-router with a state management library like Pinia. Store your flower data in your Pinia store, then navigate using just :id, and finally load flower data by id when the new view is created/mounted.

Upvotes: 1

Related Questions