Vue Router: Exploring Dynamic Routes with Example

WebCraft Notes - Jan 23 - - Dev Community

Exploring Dynamic Routes with Example

Please, check this post in my web notes.

In our previous post, we delved into the installation and setup of the Vue Router, uncovering its robust capabilities. Vue Router boasts a feature-rich functionality that, at times, may seem intricate to navigate. In this follow-up post, our focus shifts to one of its powerful features – ¨Dynamic Routes¨. Join us as we unravel the complexities, exploring how to effectively utilize dynamic routes. Through a straightforward example, we'll guide you in constructing a dynamic page capable of seamlessly receiving data from the server and dynamically rendering it on the page. So let's analyze ¨Dynamic Routes¨ with an example.

Often, we encounter scenarios demanding the association of routes with a particular pattern leading to the same component. Consider a scenario where a Post component must be shown for multiple posts, each identified by a unique post ID. Vue Router simplifies this task through the use of dynamic segments within the path, termed as "parameters" or "params." Leveraging these parameters, we dynamically match and display the Post component, responding to the specific user ID present in the URL.

In the previous post, we created a new app with Vue Router, and now we will continue working on that app.

First, we will add a ¨Post.vue¨ component inside the views folder, then import that component into our router-index.js file like this:

{
    path: '/post',
    name: 'post',
    component: () => import('../views/Post.vue')
}
Enter fullscreen mode Exit fullscreen mode

Nothing special, after that we can check URL with "/post" and there will be our empty page. Ok, so how to make it dynamic? Simple: let's add the parameter "id" into the path, after that, our path will look like "/post/:id".

Now we can update our "post" page and we will find out a warning message in console "[Vue Router warn]: No match found for the location with path "/post"", correct, now our app does not have "/post" route we can add it but we don't need it.

Let's check another route "/post/1" for example, and we will see our previous "Post" page. Let's check with "/post/1002" route and the same page. That's because we added a dynamical "id" parameter, and whatever we add in the "id" place will be accepted with Vue Router as a valid ID value.

That is a "Dynamic Route", but how can we use it? Let's check!

We will use "JSONPlaceholder" free API for fetching test data. Inside our "Post.vue" component we will add "mounted" lifecycle hook, and inside that hook, we will get the route parameter by using "$route.params" (specifically accesses the parameters object within the $route object) that will return our id from URL, and then by using that id we will fetch from API post.

Check the code and result...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .