Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Parameter on Vue Router

Tags:

So I have a project Page and when I click in one project I want to go to Project Detail page of that project. so I'm using dynamic routes. I pass as parameters a name(that will show on URL) and Id(that I use to go to my store and get the project, this Id is not showing on URL). Everything is ok, the problem is when I Load the browserinside the project Detail page, I only get name as a parameter and I cant get the Id so because of that I cant match the Id with my vuex because there is no Id.

this is my router-link on parent

<router-link class="project__icon" :project="project" :to="{ name: 'projectDetail', params: {name: project.name.replace(' ', ''), id: project.id} }">

and this is what I do on other page to get my project Id inside Vuex

const projectId = this.$route.params.id; 
    this.project = this.$store.getters.getProject(projectId);

This is what I get when I click on router

http://localhost:8080/project/myprojectName

On my router file I have this

{
 path: '/project/:name',
 name: 'projectDetail',
 component: ProjectDetail,
},
like image 479
Joao Bairrada Avatar asked Apr 24 '19 18:04

Joao Bairrada


1 Answers

I'm not sure why you are binding project to the router-link, shouldn't be necessary.

<router-link class="project__icon" :to="{ name: 'projectDetail', params: {name: project.name.replace(' ', ''), id: project.id} }">

You need to add :id as a parameter to your route. You can mark it optional with a ?.

{
 path: '/project/:name/:id?',
 name: 'projectDetail',
 component: ProjectDetail,
}

Also, if you set props: true you can decouple your component from the router and instead of using this.$route.params.id, your detail component will receive the parameters as props.

{
 path: '/project/:name/:id?',
 name: 'projectDetail',
 component: ProjectDetail,
 props: true,
}

EDIT: You have to have the id in the url if you want to allow refreshing and still keep the id or you have to store it somewhere like localstorage or sessionstorage.

like image 79
Steven B. Avatar answered Oct 05 '22 00:10

Steven B.