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

Modifications made to Vue components do not prompt Jest to automatically restart

I have a section of my package.json file that looks like this: { ... "scripts": { "test:unit": "jest --no-cache", ... }, "jest": { "transform": { "^.+\\.js$": "babel-jest", "^.+\\.vue$": "vue-jest" } ...

Issue with event listener arising once elements have been loaded into the dom

I have a project where I want to click on a category card to obtain its id and then redirect to the movies screen. I understand that using row.eventlistener() in index.js executes before the elements are rendered, causing the id not to be captured. How ca ...

Tips on preventing the need for null or undefined checks in JS/Typescript singletons that have an initialization function

Is there a way to streamline the process of handling props in an Object literal that is dynamically initialized only once? I'm looking for a pattern that would eliminate the need for repetitive null/undefined checks and throw errors when certain metho ...

What is the best way to send a JavaScript variable to a GraphQL query?

I'm struggling with making my super simple GraphQl query dynamic based on input. The query is straightforward, but I need to replace the hardcoded string of "3111" with a value from a variable called myString. How can I achieve this in JavaS ...

What could be causing req.params to come back as undefined?

I have reviewed two similar questions here, but none of the suggestions in the comments seem to be resolving my issue. app.get('/:id', function(req,res) { console.log(req.params.id); }); app.get('/:id', function(req, res) { db.que ...

Utilizing Vue.js with XML data streams

I ran into a problem while working on my personal site with Vue.js. My goal is to display the five latest posts from my Jekyll blog on the page. To achieve this, I am checking the feed at http://todayilearned.dk/feed.xml. However, I'm struggling to ...

What are the steps to create an AngularJS application with AWS integration?

Should I deploy an EC2 instance and set up a web server like Node.js on it, or is it necessary to use the AWS SDK for JavaScript? (Please note that this project involves interacting with an application server, not just a static AngularJS app) ...

Error: cannot use .json data with `filter` method from WEBPACK_IMPORTED_MODULE_2__["filter"]

There seems to be an error occurring when attempting to retrieve data from a JSON file in the specific line of code selectedEmployee: employeeList.data.Table[0], An issue is arising with TypeError: _employeeList_json__WEBPACK_IMPORTED_MODULE_2__.filter ...

Issues have been reported with the functionality of the backbone.js app when switching views, particularly regarding the inconsistent

I am in need of assistance with backbone.js. Whenever a 403 or 401 error occurs, I want to display the login view. Currently, I have attempted the following approach: $(document).on('ready', function(){ app.loadTemplates(['ShellView&apo ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

While continuing to input text, make sure to highlight a specific element from the search results list

Currently, I am using a customized search feature in my React.js application. I am looking for a way to focus on an element within the search results so that I can navigate using arrow keys. At the same time, I need to keep the input field focused to conti ...

Unable to locate 'react' for mdl module

Currently working on my first website using react, following a tutorial available at this link I am attempting to install and utilize the material lite module, but encounter a compilation error when starting npm with the following message: Error: Module ...

Retrieving properties from a selector's output function

My situation is similar to the scenario described in the accessing react props in selectors documentation. However, in my case, let's assume that the visibilityFilter is coming from the props. Is there a way to achieve something like the following? e ...

Google Analytics does not include e-commerce tracking capabilities

Testing out the e-commerce-tracking feature, I modified Google's standard-script to ensure its functionality: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i ...

Utilizing memcache in conjunction with PHP and Node.js

Can JavaScript objects and PHP associative arrays be shared with memcache? Alternatively, is it necessary to convert the data into a string before sharing them? ...

Navigating with React Router v6 beyond the confines of individual components

When using react-router v5, I would create the history object like this: import { createBrowserHistory } from "history"; export const history = createBrowserHistory(); Then I would pass it to the Router like so: import { Router, Switch, Route, Link } from ...

You can activate the ability to click on the main tag by setting routerlink as the child component in Vue

Within my HTML code, I have utilized a RouterLink within an li tag to create a basic dropdown menu. Currently, when options are displayed in the dropdown menu, I am only able to click on the text itself to navigate to the next page. However, I would like t ...

Dynamically setting properties in a Vue component using Angular

After browsing through this interesting discussion, I decided to create a web component: <my-vue-web-comp [userId]="1"></my-vue-web-comp> Initially, everything was working smoothly in Angular when I assigned a static property. Howeve ...

Bypassing redirection in Nuxt for seamless login experience

I've been exploring ways to implement authentication on my Nuxt app, but I'm struggling to find a tutorial that doesn't rely on redirecting to public or private paths. For example: if (user.isLoggedIn()) { redirect('/dashboard&apo ...

Updating state in Vue by utilizing an array of item values

Hello everyone In a simple application, I am attempting to visualize the insertion sort algorithm using Vue. I have successfully written a function that sorts a list of items and returns an array showing each step of the sorting process. The final array i ...