Passing components as props in Vue routing

Looking to extract a number from a route parameter :

routes: [{ path: '/user/:id', component: User }]

Wanting to access the prop within the User component:

export default {
    props: {
       id: Number
    }
}

Encountering an error message:

Invalid prop: type check failed for prop "id". Expected Number with value 2, got 
String with value "2".

Is there a way to automatically convert the value to a number? I explored https://github.com/posva/vue-coerce-props but believe I can achieve the same without using another extension.

Answer №1

To customize the prop for your component, you can create a computed property that transforms the prop into the desired format. Make sure to update the prop definition to allow for both strings and numbers.

export default {
    props: {
        id: {
            validator(value) {
                return !isNaN(parseInt(propVal));
            }
        }
    },
    computed: {
        parsedId() { 
            return parseInt(this.id); 
        }   
    }
}

In your code, replace usages of id with parsedId, although this workaround isn't ideal. There is an open RFC proposing separate internal and external names for props.

For vue-router, consider using the props function in route definitions to map route parameters to your desired prop structure.

You could implement something like this:

routes: [{ 
    path: '/user/:id', 
    component: User,
    props: route => ({ id: parseInt(route.params.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

"Unraveling the Mystery of jQuery In

I am facing an issue with integrating jQuery into my code. I have always followed the same method, which has worked in the past, but now it seems to be causing problems for me. I suspect it may be because I am not on my usual laptop, although when I visite ...

Enhance Your Search Functionality with an Angular Pipe

I created a custom pipe that filters the search field and displays a list of items based on the search text. Currently, it only filters by companyDisplay, but I want to also filter by companyCode and companyName. JSON [{ companyDisplay: "ABC", co ...

Extracting values from PHP using AJAX

Whenever a user clicks on the download button, a zip file is successfully created on the server with the necessary files. However, instead of getting an alert with the location of the zip variable ($zip) from PHP as expected, it shows [object Object]. The ...

import jQuery into a JavaScript file

I'm currently working on a Chrome extension that relies on background.js to perform basic tasks. I need to include jquery.js in my background.js file so that I can utilize its ajax function, but I'm unsure of how to achieve this. Is it even possi ...

A simple guide on passing a variable from Node.js to the view

Currently, I am delving into the world of Node.js and encountering a hurdle in sending a variable from app.js to index.html without relying on Jade or any other template engine. Below is my implementation in app.js: var express = require("express"); var ...

Tips for enabling/disabling a Chrome extension through the utilization of local storage in the background page

Even after reading numerous answers on similar questions, I am still facing some difficulties. My goal is to allow the user to disable my chrome extension by simply clicking on the icon at any time. The extension is designed to run once on every page load, ...

Customizing demonstration code for EventDrops with D3.js (by marmelab) - what are the best strategies?

After discovering the non-Node.js version of the EventDrops library for D3 on GitHub, I successfully implemented the example on my own server. You can find more details and the example code in this blog post here. However, I'm currently facing two is ...

Updating Property of a div in Vue.js

I have a Vue file and I am trying to specify an 'action' attribute for my form. <template> <div> <form> </form> </div> </template> export default { created() { var test = document.getElement ...

Disable automatic submission of XMLHttpRequest

I've been testing this script and it seems to be working fine, but I'm not a fan of the auto-submit feature. I tried to remove/disable it and add a regular submit button instead, but that didn't work as expected. <div id="div_data"> ...

Determine the dropdown list value by analyzing the final two variables in a textfield

In my textfield, car registration numbers are meant to be entered. These registrations are based on years in the format GT 74454 12, with the last two digits "12" representing the year 2012. I am looking for a script that can automatically detect the last ...

Refreshing the Angular resource under observation

My brain feels a bit fried today, so pardon what might seem like an obvious question. I have a useful resource at my disposal: Book = $resource("/books/:id", {id: "@id"}); book = Book.get(1); When I want to refresh the object to receive any updates from ...

Issue with triggering ReactJS onClick function accurately

For the function to work correctly, I had to add e.preventDefault(). However, my goal is for it to redirect the user to '/' after submitting the form. Below is the function that I am attempting to trigger: onAddPoints = (e) => { e.prevent ...

What is the best way to create JavaScript code specifically for devices with a maximum width of 520px?

Is there a way to apply this JavaScript code specifically to devices with a maximum width of 520px? I could use some guidance on how to achieve this. // Apply code for max-width = 520px const myBtn = document.getElementById("darktheme"); const ...

Getting the WatchPosition update just one time

I have implemented this code to continuously retrieve the first position and I need it to keep doing so. var init = function() { navigator.geolocation.getCurrentPosition(function(position) { new_position = position; }, onEr ...

Extracting information from a JSON dataset

Struggling today to figure out how to loop through and print the name of each object. Check out the JSON response below: { "placeListings": { "OBJ1": { "Active": true, & ...

Preset for Typescript in Babel 6

Can anyone help me find a Babel preset for Typescript that is compatible with Babel 6, rather than Babel 7? I've been searching for this module with no luck. Is it possible that the TS preset is not supported for Babel 6? ...

What is the best way to load the nested array attributes in an HTML table dynamically with AngularJS?

I attempted the following code, but I am only able to access values for cardno and cardtype. Why can't I access the others? Any suggestions? <tr ng-repeat="data in myData17.layouts"> <td ng-show="$index==1">{{data.name}}</td> &l ...

What could be causing the Angular router outlet to not route properly?

Check out this demo showcasing 2 outlets (Defined in app.module.ts): <router-outlet></router-outlet> <router-outlet name="b"></router-outlet> The specified routes are: const routes: Routes = [ { path: 'a', com ...

Combining Two Arrays Based on Unique Identifier

Seeking guidance on enhancing this method to eliminate the need for a workaround. I have two separate Object Arrays containing JSON data. The first array consists of all dates within a specific range, while the second array is derived from a SQL query, po ...

The issue lies with Express Mongoose failing to store the data

Encountering some issues when trying to save an object created in Express nodejs using mongoose. Despite receiving a confirmation that the object is saved, it cannot be located even after attempting to access it through the server. Express route for savi ...