What could be causing the issue of undefined component props in Vue Router?

Recently diving into the world of Vue, I've been eager to master the art of utilizing Vue router. Smooth sailing with normal routing, I decided to spice things up by experimenting with dynamic routing. To my surprise, everything ran smoothly until I attempted to pass props to these dynamic routes – causing my code to spiral into chaos.

My go-to versions for Vue and Vue router are the ones recommended by their official websites: - https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js - https://unpkg.com/[email protected]/dist/vue-router.js

The HTML structure:

<div id="app">
  <h1>{{ message }}</h1>
  <nav>
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
    <router-link to="/user/John">Name</router-link>
  </nav>
  <!-- route outlet -->
  <!-- component matched by route will render here -->
  <router-view></router-view>
</div>

The JavaScript part:

// Route components
const Home = { template: '<div>Home</div>' };
const About = { template: '<div>About</div>' };
const User = { props: ['name'], template: `
    <div>
      <div>User {{ name }}</div>
      <button @click="checkName">Check</button>
    </div>`,
    methods: {
      checkName: function() {
        console.log('Params name: ' + this.$route.params.name);
        console.log('Props name: ' + this.name);
      }
    }
  };

// Routes for router
const routes = [
  { path: '/', component: Home },
  { path: '/home', redirect: Home },
  { path: '/about', component: About },
  { path: '/user/:name', component: User, props: true }
];

const router = new VueRouter({
  routes: routes
});

const app = new Vue({
  el: '#app',
  data: {
    message: 'VueJS Router'
  },
  router: router
});

Upon navigating to the 'Name' page, the static text displays just fine while the dynamic text falls short. I inserted a button that logs the value of the name from both props and $route.params for the user's clarity. Surprisingly, clicking the button reveals an undefined value for the name in props but the correct one for the name from params. What could be causing this discrepancy?

Answer №1

If you're sticking with [email protected] or lower :
The name that you are looking for is not passed as a prop, but rather as a route parameter. For more information on this, refer to Dynamic route matching.

To access it from your template, use the following syntax: $route.params.name.

You could also consider using a computed value instead.

If you can update VueRouter
As mentioned in another response and in the release notes of [email protected], support for passing route params down as props was introduced in version 2.2.0, while you were previously using version 2.0.0. To utilize props, you will need to update to (at least) version 2.2.0.

Answer №2

When trying to install Vue Router, I encountered an issue with the CDN link provided on their installation page being outdated. The link was supposed to be:

https://unpkg.com/[email protected]/dist/vue-router.js

The correct updated link that should be used is:

https://unpkg.com/[email protected]/dist/vue-router.js

You can find more information about this issue and the solution in this forum post: https://forum.vuejs.org/t/why-is-component-props-undefined-vue-router/34929/5

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

Trigger a single occurrence of the function upon element creation and pass it to VueJS methods

Currently, I am working with BootstrapVue and would like to provide a brief overview of my code: I have a v-for loop with inputs that can be dynamically created using a b-button named "addElement". Additionally, I have the option to select an item from a ...

Determining if an element corresponds to a By-object in Selenium using JavaScript

Is it possible to determine if a given WebElement matches a specific By object? The function should return either true or false. For example: foo(myWebElement, By.className("myClass myClass2")); foo(myWebElement, By.css("div")); foo(my ...

A modern web application featuring a dynamic file treeview interface powered by ajax and php technology

Currently, I am developing a web-based document management system that operates as a single page using an ajax/php connection. The code snippet below shows how I display folders and files in a file tree view: if (isset($_GET['displayFolderAndFiles&apo ...

Is it possible to exchange CSS classes for a specific group of elements using JQuery?

I have two list items listed below: <li name="luxury" class="cars luxury> <div id="featured_lux" name="featured" class="carImg_lux col2_lux "> My Luxury Car<img border="0" class="car-im ...

Perform an HTTP POST request in Angular to retrieve the response data as a JSON object

I am currently in the process of developing a simple user authentication app. After completing the backend setup with Node.js and Passport, I implemented a feature to return JSON responses based on successful or failed authentication attempts. router.pos ...

What is the best way to add content to the ajax success code?

For my project, I have a lot of content in the success function of AJAX. I plan to move this content to a file called textcsc.js and use the include() method in AJAX. Initially, the code was working successfully: $(document).ready(function() { $(&apo ...

Return to the initial stage of a multistep process in its simplest form following a setTimeout delay

I recently customized the stepsForm.js by Copdrops and made some modifications. Although everything works well, I'm struggling to navigate back to the initial step (first question) after submitting the form due to my limited knowledge of JavaScript. ...

Maintaining the $index value across all pagination pages in AngularJS while matching it with the items in the data list

Is there a way to maintain the original $index numbers in my list data after pagination? For example, if data.length is 50 and they start from index 0, the first page contains 10 items ending at index 9. The next item on the second page should start at in ...

Google Maps is experiencing difficulties with loading

Important Note: I have decided to create a new question regarding this issue. I recently inquired about the Google Maps rendering problem. The response seemed straightforward, but my code appears as follows: var map; function initialize() { var m ...

What is the best method for rotating segments in THREE.TubeGeometry?

I've successfully generated a flat tube structure using THREE.TubeGeometry with radiusSegments set to 2. However, once added to the scene, it appears perpendicular to the ground: https://i.sstatic.net/U3qTt.png Is there a way to rotate each segment ...

Ways to prevent the movement of changing centered text

After recently downloading a text rotator plugin, I've run into a small issue. Whenever the text changes, the entire heading shifts because it's centered. Here's a simple example: (Don't worry about the js code, it's just a ba ...

Having trouble launching the emulator in VS Code for React Native?

I'm having trouble launching the android emulator on VS Code to run React-Native. I already have an emulator set up in Android Studio, but when I try to launch it, I get the error message: Error Failed to launch emulator. Reason: No emulators found as ...

When fetching data from the API in Angular, the response is displayed as an object

After fetching data from the API, I am encountering an issue where the "jobTitle" value is not displaying in the table, but instead appears as an array in the console. Can someone assist me with resolving this problem? Below is the visibility.ts file: exp ...

Incorporate a JavaScript variable into an HTML href link for dynamic web content

This is a snippet from my code: <p id="demo">{$value.file_name}</p> <script type="text/javascript"> var str = document.getElementById("demo").innerHTML; var res = str.replace("/var/www/html/biology/demo", ""); document.getElementById(& ...

Hide specific content while displaying a certain element

Creating three buttons, each of which hides all content divs and displays a specific one when clicked. For instance, clicking the second button will only show the content from the second div. function toggleContent(id) { var elements = document.getEl ...

Obtaining the image with PHP

As a newcomer to PHP and Ajax queries, I am trying to utilize the croppie.js plugin to upload a profile image. However, when I upload the image, it is saved as 1580192100.png. The problem arises when attempting to later retrieve the image based on the user ...

Converting objects into JSON format

I'm trying to transform an object that looks like this: { user[id]: 1, user[name]: 'Lorem', money: '15.00' } Into the following structure: { user: { id: 1, name: 'Lorem', }, money: ...

Best practice for passing a variable argument in a JavaScript callback?

After searching the internet without success, I couldn't find the answer to my problem. The issue revolves around a function that I have: function ParentFunction (DataBase, Parameters) { for (k = 0; k < DataBase.length; k++){ var ...

Tips for displaying consecutive information from a Sequelize query with associations in Node.js

Attempting to create a straightforward sequential output from a demo Node.js app and Sequelize has proven to be challenging for me. I'm struggling to comprehend how promises and Bluebird can assist me in achieving the desired result: User: John Doe ...

Having trouble creating an alias system in discord.js and encountering errors

While developing an alias system for my Discord bot, I encountered a situation where I wanted to display the message: "if the user entered the wrong command name or alias then return: invalid command/alias". However, when implementing this logic, ...