I am trying to pass data from one route to another. However, I need to pass an ID and title to the child route and use only the title in the URL but not the ID. I will use the ID to fetch data. I have read everywhere and I cannot think of a solution to my problem.
Example:
Let's say we are at route called "Library", where we have different books. When clicking on one of the books, I want to go to another route, which will display the book title in the URL and have the ID usable for data fetching. How can I do that?
I have found how to do dynamic URL matching, which I can use for the title display but then I cannot pass the ID:
<router-link :to="{path: '/Book/' + book.title}">
I have also found how to pass parameters using named routes but then how do I use the title in the URL?
<router-link :to="{name: 'Book', params: {title: book.title}}">
I am sure I am missing something here but I am not entirely sure what.
You could use props
:
router/index.js:
routes: [
{ path: '/Library/:title', name: 'Book', component: Book, props: true },
...
]
navigation:
:to="{ name: 'Book', params: { title: book.title }, props: { id: book.id } }"
Book.vue
export default {
props: {
id: {
type: String,
required: true
}
}
}
Instead of props: true
in router definition you can pass defaults, i.e:
..., props: { id: '1' }
Be weary of using title in url, it might need escaping. I know it's good for SEO, but ids are safer.