Route params changes Type
to String when I input from url
to Number when passed from router-link .
router.js
{
path: '/post/:id',
name: 'postdetails',
component: () => import('./components/PostDetails.vue'),
props: true,
}
when I use the "router-link" it will pass the prop as type "number"
<router-link :to="{name:'postdetails', params:{id: post.id}}">
<div class="title" @click="viewPost">
<h4>{{post.user_username}} -</h4>
<p>{{post.title}}</p>
</div>
</router-link>
if I click the element inside router-link it will redirect to another page and the "params.id" is type Number .
export default {
name: "PostDetails",
props: {
id: Number
},
created() {
console.log(this.id);
}
};
But when I input it on Url like this:
http://localhost:8080/post/1
the params prop becomes String
how can I stop the params prop Type from constantly changing?
If you want to maintain the route params to a certain Type weather it was entered from a url or sent via router-link you can do it by adding a condition on the router props.
{
path: '/post/:id',
name: 'postdetails',
component: () => import('./components/PostDetails.vue'),
props(route) { // we keep the params.id Type from changing when entered from url
let props = { ...route.params }
props.id = parseInt(props.id)
return props
},
},
now the Id in the props will always be a Number Type, even if entered from url.
there is a forum from vuejs similar to this
Regarding your question, you can create a computed property, which transforms the received parameter to the type you wish. Trivial implementation to convert it to string:
computed: {
idStr: function() {
return this.id + '';
}
}
Check the comment I left to understand what is happening under the hood.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.