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

Tips for implementing daterangepicker js in an Angular 2 project

I'm currently working on an Angular 2 project and I'm looking to integrate the daterangepicker.js library for a date range picker. If you're not familiar with it, you can find more information about the library here. Here's the HTML co ...

Integrating axios interceptors with Vue.js custom components to create a versatile method for presenting error messages across the board

If we consider the following code snippet: axios.interceptors.response.use(function (response) { return response; }, function (error) { if (error.response.status === 400) { if (error.response.data.type === "fieldsValidationErrors") { openMod ...

Enhancing React components with dynamic background colors for unique elements

I am encountering an issue while using a map in my code. Specifically, I want to set the background of a particular element within the map. The element I am referring to is "item .title". I aim for this element to have a background color like this: https:/ ...

Encountered CSRF validation error while working with a Python Django backend in conjunction with React frontend using Axios for making POST requests

I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function ...

Adjusting the color of a cell based on its value

Currently, I am in the process of converting a CSV file to an HTML table by utilizing a tool available at . However, I am facing a challenge in modifying the background color of cells based on their values. I would greatly appreciate any help or guidance w ...

Showing an image stored in an array using JavaScript

This script is designed to pull images from a specific location on an HTML page. images = new Array(); images[0] = new Image(); images[0].src = "images/kate.jpg"; images[1] = new Image(); images[1].src = "images/mila.jpg"; document.write(images[0]); I&a ...

Instance of a Component Available Worldwide

When working with Vue 2.x in our production applications, we utilize a toast component. This toast component is mounted once through a plugin (code provided below) and then added to the Vue prototype for easy access in every component instance. This setup ...

Troubleshooting issue with Vue Class Component and Vuex-class causing ESLint error

I am interested in utilizing vuex-class to bind helpers for vuex and vue-class-component However, an error message is displayed: Error: Parsing error - Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class ...

Acquiring an icon of a program using its handle

I am looking for a way to extract a program's icon from its handle, which I acquired using User32.dll with EnumWindow/FindWindow. While I am aware of ExtractAssociatedIcon, it seems to work from a file instead of a handle. My question is how can I con ...

What is causing my grayscale function to only impact part of the canvas?

As a beginner programmer, I have been experimenting with creating a grayscale function in JavaScript for practice. This is the code I have come up with: <canvas width='400' height='400'></canvas> <script> var can ...

Expiration Date of Third-Party Cookies

I need help retrieving the expiration date of a third-party cookie programmatically using JavaScript. Even though I can see the expiry time in the browser's DevTools (refer to the screenshot at ), I am struggling to figure out how to access this infor ...

Why does my JSON variable contain "type" and "data" values instead of something else?

After using JSON.stringify() on my object to save it to a file, I noticed that one of the parameters does not have the expected string value assigned. Instead, it has a "type" and "data". Code: fs.writeFileSync('myjson.json', JSON.stringify(myjs ...

In my sequence of Promises, a "reject is not defined" error led to the rejection of a Promise

In my code, I set up a chain of Promises like this: let promise = new Promise((resolve, reject) => { imgToDisplay.onload = () => { resolve(imgToDisplay.width); } }) .then((result) => { window.URL.revokeObjectURL(imgToD ...

What enables typescript to be eligible for transpiling is its equivalent level of abstraction to javascript?

Transpilation is the act of converting code from one language to another with a similar level of abstraction. Can you point out some distinctive characteristics that indicate TypeScript transpires into JavaScript? ...

The problem with asynchronous requests in Ajax

In the code below, I have noticed that when an alert() box is used and then clicked, the content loads on the page. However, without the alert() box, the content does not load. I've tried researching 'Ajax' requests extensively but still can ...

Angular 2 signal sender

I have a specific class definition for my Project: export class Project { $key: string; file: File; name: string; title: string; cat: string; url: string; progress: number; createdAt: Date = new Date(); constructor(file: File) { th ...

How to dynamically populate a select option with data from a database in CodeIgniter 3 and automatically display the result in a text

How can I fetch select options from a database in CodeIgniter 3 and display the result in a text field and span area? Currently, I am only able to display data from the row_name when an option is selected. Here is my current implementation: <?php $query ...

Is SWR failing to provide outdated data?

My understanding was that SWR should display the cached data upon page load before refreshing with new information from the API. However, in my Next.js app with a simple API timeout, the "loading" message appears every time due to the 5-second delay I adde ...

Issue with the dynamic updating of props

Every time a radio button is clicked within Test.js, the handleclick function executes, updating an array. However, the issue lies in not sending this updated array back to graph_test.js. As a result, graph_test.js only receives the initial array filled wi ...

Internet Explorer versions 9 and 10 do not support the CSS property "pointer-events: none"

In Firefox, the CSS property pointer-events: none; functions properly. However, it does not work in Internet Explorer 9-10. Are there any alternative approaches to replicate the functionality of this property in IE? Any suggestions? ...