Using vue.js to pass route parameters to a component

I'm encountering an issue with passing a route param directly into a component. Despite following various sets of instructions from the documentation (including using the Composition API as shown in the code snippet below), I continue to receive undefined when CourseModule.vue initially loads.

Route Definition

  {
    path: '/module/:id',
    name: 'Course Module',
    props: true,
    component: () => import('../views/CourseModule.vue'),
  },

CourseModule.vue:

<template>
    <div class="AppHome">
        <CustomerItem />
        <CourseModuleItem :coursemodule-id="this.CoursemoduleId"/>
    </div>
</template>
<script>
import { useRoute } from 'vue-router';
import CustomerItem from '../components/customers/customer-item.vue';
import CourseModuleItem from '../components/coursemodules/coursemodule-item.vue';

export default {
  setup() {
    const route = useRoute();
    alert(`CourseModule.vue setup: ${route.params.id}`);
    return {
      CoursemoduleId: route.params.id,
    };
  },
  components: {
    CustomerItem,
    CourseModuleItem,
  },
  mounted() {
    alert(`CourseModule.vue mounted: ${this.CoursemoduleId}`);
  },
};
</script>

coursemodule-item.vue:

<template>
  <div id="module">
    <div v-if="module.data">
      <h2>Course: {{module.data.ModuleName}}</h2>
    </div>
    <div v-else-if="module.error" class="alert alert-danger">
      {{module.error}}
    </div>
    <Loader v-else-if="module.loading" />
  </div>
</template>

<script>
import Loader from '../APILoader.vue';

export default {
  props: {
    CoursemoduleId: String,
  },
  components: {
    Loader,
  },
  computed: {
    module() {
      return this.$store.getters.getModuleById(this.CoursemoduleId);
    },
  },
  mounted() {
    alert(`coursemodule-item.vue: ${this.CoursemoduleId}`);
    this.$store.dispatch('setModule', this.CoursemoduleId);
  },
};
</script>

The alerts display the following information:

CourseModule.vue setup: zzyClJDQ3QAKuQ2R52AC35k3Hc0yIgft

coursemodule-item.vue: undefined

CourseModule.vue mounted: zzyClJDQ3QAKuQ2R52AC35k3Hc0yIgft

It is evident that the path parameter functions correctly at the top level Vue, but it still does not get passed into the component.

Answer №1

When you pass your kebab-cased :coursemodule-id props to the CourseModuleItem component, they will be converted into camelCased coursemoduleId props

Learn more about Prop Casing (camelCase vs kebab-case)

Give this a try

// coursemodule-item.vue
...
props: {
  coursemoduleId: String,
},
...
mounted() {
  alert(`coursemodule-item.vue: ${this.coursemoduleId}`);
  this.$store.dispatch('setModule', this.coursemoduleId);
},

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

The head.js feature similar to "Modernizr" does not recognize ms-edge

It has come to my attention that the head.js script is unable to detect the Microsoft "Edge" browser correctly. In addition, it erroneously adds classes like chrome and chrome55 to the <html> element. Is there a better way to handle this issue? The ...

Automated tool for generating random JSON objects

Looking for a tool that can generate random JSON objects? I'm in need of one to test my HTTP POST requests and incorporate the random JSON object into them. Any recommendations? ...

The error message "Next.js 14 does not recognize res.status as a function"

I'm a newcomer to Next.js and I've been wrestling with an issue all day. Here's my API for checking in MongoDB if a user exists: import {connect} from '../../../../lib/mongodb'; import User from '../../../models/userModel&ap ...

Change the price directly without having to click on the text field

Our Magento marketplace site is currently utilizing the code below for updating prices. However, we are looking to make the price field editable without requiring a click on the textfield. This means that users should be able to edit the price directly wi ...

The beforePopState event in next/router is not triggering as expected

Noticing an issue where the beforePopState event is not triggering when I use the back button. This code snippet is part of a hook defined in _app.js according to the documentation. The current version being used is 12.1.5 If anyone has insights on what ...

An Angular directive utilizing dual aliases

Is there a simple method to give a directive two distinct names? For example: app.directive(['directiveNameOne', 'directiveNameTwo'], function() {...}); I have created a directive that handles both radio buttons and checkboxes in th ...

Implementing Ionic 4 with HTML2Canvas technology

Looking for a way to convert HTML into an image within an Ionic 4 application. I attempted to use html2canvas, however, it was unsuccessful and displayed the following message in the console: Below is the code snippet I used: var element = document.getEl ...

Trouble with Bootstrap Collapse feature not collapsing on its own

I recently added a Bootstrap collapse feature to my payment view in Laravel. The Bootstrap section collapses when clicked, but I would like it to be collapsed by default. I understand that I need to include: aria-expanded="false" However, it still doesn& ...

Toggle the visibility of table rows based on a specific class using a checkbox

I am currently working on a code that displays the results of a query in a table format. I would like to have the ability to click on certain elements to show or hide them. I know this can be achieved using toggle and CSS, but I keep encountering obstacles ...

Is there a way to change the font size with a click in JavaScript or Angular?

Here is a breakdown of the 4 steps: 1.) Begin by clicking on a category 2.) The filtered products will be displayed 3.) Select the desired products from the filter 4.) Once selected, the products will appear in the rightmost part of the screen within t ...

I am unable to eliminate the parentheses from the URL

I am in need of creating a function that can extract the content inside "()"" from a URL: Despite my efforts, the function I attempted to use did not provide the desired result. Instead of removing the "()" as intended, it encoded the URL into this format ...

Accessing the Nuxt store in module mode from a JavaScript file

I'm facing a challenge with my Nuxt app, where I have an AuthService within a namespaced store. The issue lies in how to import the store into my AuthService so that I can commit mutations from there. In some examples I've seen, the store is imp ...

Exploring potential arrays within a JSON file using TypeScript

Seeking guidance on a unique approach to handling array looping in TypeScript. Rather than the usual methods, my query pertains to a specific scenario which I will elaborate on. The structure of my JSON data is as follows: { "forename": "Maria", ...

What is the best way to implement multilanguage support in nodejs without relying on cookies or external modules?

Currently, I am in the process of transitioning all my projects to node.js in order to enhance my JavaScript skills. Using Node.js along with the Express module, one of my clients who runs a translation company has requested that I incorporate two language ...

Strategies for refining the names in the dropdown options using AngularJS

I am working with a select element that has a name and id as options value. I am also adding '-' along with the name. However, there is a scenario where the name will be empty and in that case, the '-' should not be displayed. The expe ...

"Eliminate the headers of columns within the collapsible rows on the ui-grid interface

I am working with an expandable table and trying to figure out how to hide the column headers for only the expandable rows within the table. I experimented with including showHeader : false in the subGridOptions, but without success as the headers are stil ...

Attempting to transfer elements from an iteration into a separate array

Currently, I am attempting to insert an associative array into an object that is empty. However, I keep encountering the following error message: An undefined property '#<Object>' cannot be read Here is the code snippet that I am testing: ...

While developing an exam portal with Angular and Spring Boot, I encountered an issue when trying to incorporate a name field as [name]

Component.html <div class="bootstrap-wrapper" *ngIf="!isSubmit"> <div class="container-fluid"> <div class="row"> <div class="col-md-2"> <!- ...

Selecting radio buttons using Bootstrap and JavaScript

I'm interested in incorporating this bootstrap radio selection feature into my JavaScript code. For example, if option1 is true, I want to execute a specific action... How can I achieve this? <div class="alert alert-info" role="alert"> < ...

Is there a way to dynamically assign column names during the import process?

In my current scenario, I am importing data from various sources into my JSON backend. The mapping file will resemble the sample below. The question is how can I efficiently utilize this mapping during data import into my backend. The idea is to provide t ...