Sending a property as a parameter to a different component through Vue's router-link

I have a component designed to showcase recipes in a list format. Each recipe is rendered using a separate component from an array of recipes. I am currently attempting to pass the recipe object from one component to another component using Router-Link

      <RecipeCard
        v-for="recipe in filteredRecipes"
        :key="recipe.id"
        :recipe="recipe"
      />

The RecipeCard component code snippet looks like this:

<template>
  <div>
    <router-link :to="{ path: 'recipe/' + recipe.id, props:{recipe} }">
        <div>{{ recipe.title }}</div>
        <p>
          {{ recipe.description }}
        </p>
    </router-link>
  </div>
</template>

To display more detailed information when a recipe card is clicked, the recipe should be passed to another component. Upon clicking the router-link, it leads to the following page:

<template>
  <div>
    <div>{{recipe.id}}</div>
  </div>
</template>

<script>

export default {
  name: 'PageViewRecipe',
    props: {
      recipe: {
        type: Object,
        required: true
      }
    },
  data() {
    return {
    };
  }
};
</script>

<style></style>

The recipe object contains additional details beyond what is displayed.

import Vue from "vue";
import Router from "vue-router";
import Home from "./pages/PageHome";
import AddRecipe from "./pages/PageAddRecipe.vue";
import PageViewRecipe from "./pages/PageViewRecipe.vue";

Vue.use(Router);

const router = new Router({
  mode: "history",
  routes: [
    {
      path: "/",
      name: 'Home',
      component: Home,
    },
    {
      path: "/add-recipe",
      name: 'AddRecipe',
      component: AddRecipe,
    },
    {
      path: "/recipe/:id",
      name: 'ViewRecipe',
      component: PageViewRecipe,
      props: true
    }
  ],
});

export default router;

Despite my efforts, I am encountering difficulties passing the prop to the final component. I have attempted using params, but so far no solution has worked.

Answer №1

When utilizing the vue-router, issues may arise with passing props from a <router-link /> to a component rendered in a <router-view />. Furthermore, the <router-link /> does not recognize the props key within the to parameter.

To resolve this, you can:

  1. Implement any state management approach as outlined in the official documentation, allowing both PageViewRecipe and RecipeCard access to the same list of recipes.

  2. In the PageViewRecipe component, pass the id as a parameter to the router-link. For example:

<!-- You do not necessarily have to manually create the path; let vue-router generate it by combining named routers and parameters -->
<router-link :to="{ name: 'ViewRecipe', params: { id: recipe.id } }">
  <div>{{ recipe.title }}</div>
  <p>
    {{ recipe.description }}
  </p>
</router-link>
  1. Inside the PageViewRecipe, retrieve the list of recipes from a shared location (such as vuex, a shared object, etc) and locate the recipe based on the provided id:
<template>
  <div>
    <div>{{recipe.id}}</div>
    <p>
      {{ recipe.description }}
    </p>
  </div>
</template>

<script>

export default {
  name: 'PageViewRecipe',
    props: {
      // Provided by vue-router (from URL), accessible as this.$route.params.id
      id: {
        type: Number,
        required: true
      }
    },
    computed: {
       recipe() {
         // `this.recipes` is sourced from the state management system (e.g., vuex getter)
         return this.recipes.find(recipe => recipe.id === this.id);
       }
    }
  }
};
</script>

<style></style>

This method allows for only one API request and grants the ability to handle situations where the specified recipe ID does not exist. Alternatively, consider making two API calls to avoid managing shared state.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to get getInitialProps working in dynamic routes with Next.js?

I am encountering an issue. The return value from the getInitialProps function is not being passed to the parent component. However, when I console.log the values inside the getInitialProps function, they appear to be correct. Here is the code snippet: i ...

Using async functions with Vue.js

In my Vue.js component, I have the following code snippet: module.exports = { data: function () { return { searchText: "", searchResult: [] } }, watch: { searchText: function() { ...

What is AngularJs's preference: URL or ID for templateUrl?

When looking at the AngularJS documentation, you will come across an example using the templateUrl property: In the HTML: //ngApp... <div ng-controller="Ctrl"> <div my-customer></div> </div> And in the controller: . ...

Issue with konvaJS when trying to simultaneously resize, drag, and apply filters to an image

Looking for help with resizing, dragging, and filtering images using Konvajs 2d canvas library? If the images are not resizing properly after applying a filter, can someone assist me? Note: Please be aware that when using Google image URLs, there may be c ...

Transferring information from dynamic elements to a higher-level component as an object

I've developed a dynamic form feature that renders a set of inputs, giving users the ability to add or remove input fields based on their needs. Here is an example: The "item" inputs are rendered using dynamic components: <component v-for="itemR ...

Using Vue.js 3 to fetch data from a REST API using the Axios

How do I properly retrieve and display an array using axios.get in Vue? The data is not showing up in my table cells when I use the v-for directive. Could the issue be related to the v-for statement? <tr v-for="params in form" :key=" ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

Is it possible to automatically close navigation dropdowns when the screen size changes?

I am using a bootstrap 4 navbar with dropdowns that open with CSS animation/fade-in on desktop, and a separate toggle button for mobile. Everything works fine, but when I open the dropdowns on mobile and then resize the window screen, they remain open whic ...

Creating an HTML form to collect user data and then automatically saving it to an Excel file stored in a shared Dropbox account

I am looking to extract data from a user form on a website and then automatically save it as an Excel file in a designated Dropbox account once the user clicks submit. Instead of receiving multiple emails every time the form is filled out, I would like t ...

Developing a jQuery loop

I am in the process of creating a function that will change the background color (color A), box color (color B), and text color (color A) when a user clicks on the refresh button. I have already defined an array called 'colors', but I am struggli ...

What is the method for displaying script commands within package.json files?

With a multitude of repositories, each one unique in its setup, I find myself constantly referencing the package.json file to double-check the scripts. "scripts": { "start": "npm run dev" "build:dev": "N ...

Ensure jQuery waits until the function has completed execution

Here is the script in question: var d; $(".circle").click(function() { var id = $(this).attr('id'); var MyDiv1 = document.getElementById(id); var name = MyDiv1.innerHTML; $.get("url", function(data){ d=data; }); d=d ...

Establishing the maximum width of a Vuetify expansion panel component

I'm currently in the process of developing a webpage using vuetify and nuxt. My main focus right now is adjusting the max-width property of the expansion panel UI component (https://vuetifyjs.com/en/components/expansion-panels). Here's the code s ...

Issue with specific route causing server to throw 500 error

Recently, I have been working on a small school project that involves creating our own API and connecting it to an Angular front end. While following some tutorials, I encountered an issue where my application started throwing internal server error 500 af ...

I'm curious if there is a method to indicate the specific destination within a separate file that the FS module in Node.js writes the data

Whenever I utilize the fs method fs.appendFileSync(example.json, jsonString, {'flags': 'a+'});, it successfully writes the data to the JSON file. However, the problem is that the data is not inserted into the array where I actually need ...

Ways to incorporate a custom JavaScript function that is activated by an external server system?

I'm currently exploring a JavaScript widget that needs to operate within specific constraints: The widget initiates a request to a third-party server using a callback URL The third-party server pings the callback URL after a set period, triggering a ...

Developing an object that displays animated effects when modifying its properties, such as visibility, and more

Exploring the realm of animations in JavaScript and AngularJS has led me to the idea of creating a unique JavaScript object. Imagine having the ability to define an object where setting an attribute like obj.visible = true Would automatically make the ...

Error occurs in Angular 10 when reloading IFrame

My goal is to fetch the HTML string from an API and update an iframe with that string. The code works perfectly for the first load, but when the onBtnClick method is triggered a second time, it throws an error: VM3012:1 Uncaught SyntaxError: Identifier &ap ...

Downloading Files Using Ajax and Javascript

When a client makes a request through XMLHttpRequest, the information is sent to the server. The server compiles a CSV file and sends it back as the output stream of the response to the client. Next, the client's browser should display a download dia ...

The React lifecycle method componentDidMount is failing to execute

In my React application, I have the following route setup: <Route path={`${this.props.match.path}horoskop`} render={() => <HoroscopeController horoscopeService={this.horoscopeService} fortuneTellerService={this.fortuneTell ...