Navigating through Router Parameters in VueJS

Currently, I am in the process of developing a blog using Vue.js and I am still learning the ropes.

To explain briefly, I have a list of dynamic elements that are displayed on the screen. When a user clicks on one of these items, I want to navigate to the respective page with all the related data. To achieve this, I followed a similar approach as I would if I were working with React.

Router Configuration (Router.js)

export default new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",
      name: "Home",
      component: Home
    },
    {
      path: "/post/:id",
      name: "PostView",
      props: true,
      component: PostView
    }
  ]
});

I have set up my router to handle dynamic links effectively.

Component Responsible for Generating List Data

<template>
  <router-link v-bind:to="{ path: 'post/' + post.postId, params: { post } }">
    <div> .... </div>
  </router-link>
</template>

<script>
import moment from "moment";

export default {
  name: "recentPostTile",
  props: {
    post: Object,
  },
};
</script>

As illustrated above is how I used the router-link. In my actual Page View, this is the method I attempted to retrieve the data in two different ways:

  props: {
    post: Object
  },

AND

  data() {
    return {
      postData: this.$route.params.post, (also tried with $route)
    };
  },

Unfortunately, when I try to log or display the post/postData, it returns undefined. Despite the fact that the data is hardcoded into the browser, it seems inaccessible. Additionally, I experimented with passing the parameters as key-value pairs without success. Creating a new variable for the data being passed through the link did not yield any positive results either. I have yet to experiment with query parameters due to aesthetic concerns regarding the appearance of the link.

Answer №1

Make a simple adjustment to your link code:

<router-link :to="{ name: 'PostView', params: { id: post.postId, postData: post } }">
   <div> .... </div>
</router-link>

Key modifications:

  • Utilized the name attribute for specifying the route
  • Eliminated the hard-coded path reference
  • Transferred the id parameter in line with the route definition's designated param name (/:id)

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

Modify radio button colors upon selection with a variety of colors

Looking to create Yes/No buttons that start with a default state of null and change color when pressed - green for yes, red for no. Check out this example code: <label class="formheading">Apparatus group is correct</label> <fieldset data-r ...

Fragment errors detected in the Menu Component

I am facing an issue with my code where I am getting an error in the console saying that the Component cannot receive fragments as children. How can I remove the fragments while retaining the logic? Every time I attempt to remove the fragments, I encounter ...

Extracting <p> elements from a separate HTML file and cycling through them

I successfully created a website using only HTML, JavaScript, and jQuery without any server-side scripting or language. Within my website, I have a simple stream.html page that remains unstyled with no CSS formatting. <html> <head> </head& ...

JSON does not send information to the specified web address

Attempting to send some data to the following URL: " $(function() { var frm = $(document.myform); var data = "?lm_po_id=154668&authentication=ThisisAuth&description=ThisIsDesc";//JSON.stringify(frm.serializeArray()); ...

When attempting to render mathML in a canvas on Safari, the image load callback does not properly trigger, resulting in

I am currently working on rendering mathML into an HTML5 canvas. One suggestion I received was to embed the mathML as an SVG foreign object, render it into an image, and then display the image within the canvas. However, this method works fine in Firefox ...

Ensure the div element remains fixed at the top of the page

I created a script to identify when I reach the navigation bar div element and then change its CSS to have a fixed position at the top. However, I am encountering an issue where instead of staying fixed, it jumps back to the beginning of the screen and fli ...

Transferring properties from the main layout to a specific component

Recently delving into the world of Vue, I find myself in need of passing props from a layout to a global component. Although my search skills may not be up to par, I have been tinkering with a default layout setup as follows: layouts/default.vue <templ ...

Discovering ways to fetch an array of objects using object and arrays in JavaScript

When comparing an array of objects with a single object and listing the arrays in JavaScript, specific conditions need to be met to retrieve the array of objects: If the itemvalue and idvalue are the same, check if the arrobj cid has the same codevalue ...

Using jQuery combogrid to automatically target and populate input box upon row selection

I have implemented combogrid functionality from https://github.com/powderblue/jquery-combogrid to display suggestions while typing. $(".stresses").combogrid({ url: '/index/stresssearch', debug: true, colModel: [{'col ...

jQuery width property does not seem to be functional on menus that do not contain any dropdown

I am currently working on creating a menu that displays arrows underneath the items when hovered over or when the .active class is added to the menu. Everything is working fine, except for the fact that it only works on menus with drop-downs and the child ...

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

Learn the steps to initiate a Vimeo video by simply clicking on an image

I have successfully implemented some code that works well with YouTube videos, but now I am looking to achieve the same effect with Vimeo videos. Does anyone have suggestions on how to do this? I need to replace the YouTube description with Vimeo, but I&ap ...

What could be the reason for the scope being empty in my AngularJS application?

I'm new to Angular and I'm currently customizing the tutorial for my app. However, I'm facing an issue with adding routes to my app. The templates are not being read correctly and the controller seems to have some issues as well. In order to ...

Creating a component in Vue to showcase Axios, based on a straightforward example from the documentation

I apologize in advance for what may seem like a trivial question, but I assure you that I have put in a considerable amount of effort to solve this problem without success. In my appService.js file, I am making an API call as follows: import axios from &a ...

Getting the Value from a Promise into a Variable in a React Component

I am currently immersed in a React project where I am utilizing the Axios library to retrieve data from an API and store it in a variable. After scouring the internet, it seems that the only method available is through Promise.then(), but this approach si ...

Java REST service remains out of reach for JavaScript fetch call

Currently, I am in the process of learning about REST API. My goal is to make a call to a POST service implemented in Java from Javascript using fetch. However, I have encountered an issue where the request fails to reach the service whenever the @Produces ...

The css-loader is missing the required dependency peer Webpack5, causing a resolution error

Recently, I've ventured into the world of JavaScript and I'm looking to incorporate vue-audio-visual into my project. However, I encountered a perplexing error in my node console that seems unrelated. The npm error message reads as follows: code ...

Can you provide me the steps to delete the title attribute from images in Wordpress?

My client has expressed dissatisfaction with the tooltip that appears when hovering over images in certain browsers, particularly Safari. This tooltip displays the title attribute within the img tag, which is a requirement enforced by Wordpress. Even if w ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...

Troubles with setting up slash commands in discord.js v13

I am encountering an issue while trying to deploy a slash command. The error message DiscordAPIError[50035] is displayed, stating "Invalid Form Body guild_id[NUMBER_TYPE_COERCE]: Value \"undefined\" is not snowflake." const path = require('n ...