Modern web applications are highly complex, often including multiple hierarchies, routes, and paths; on its own, static routing, in which manually defined routes are non-adaptive and have a fixed value, is no longer sufficient to meet the demands of modern developers and app users.
As the name suggests, dynamic routes are far more flexible. A dynamic route lets us define multiple paths to display information according to real-time network changes. We can use dynamic routing to make URLs more memorable and user-friendly, creating pages that are similar but contain different data.
In this tutorial, we’ll explore dynamic routing in Vue using Vue Router, learning how it can improve our app’s performance. Let’s get started!
In order to understand dynamic routing in Vue, first, we’ll set up a new Vue application using either the Vue CLI or Yarn, respectively:
# Vue CLI npm install -g @vue/cli # yarn yarn global add @vue/cli
Run the code below to verify that Vue was properly installed:
vue --version
Now, with Vue installed, we can create a new application as follows:
vue create routing-example
To create a route in Vue, we’ll need to define a path linking to the specific component that we want to display once the URL is loaded.
For our example, we’ll create an application with two pages, a homepage and a blog page. Let’s define the views for these two pages:
Note: For simplicity, the code below does not contain any styling or content for our two pages, focusing instead on the routing components:
// /views/Home.vue <template> <div> <h1> Welcome to Home page </h1> <p>This is the page that opens on <strong>/</strong> route</p> </div> </template> // /views/Blogs.vue <template> <div> <h1> Welcome to blogs page </h1> <p>This is the page opens on <strong>/blogs</strong> route</p> </div> </template>
Next, let’s add two static routes to our components. We’ll also define a component to show when the route is reached. Create a separate folder called routes
; inside, create a file called index.js
and add the code below:
// /router/index.js import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import Blogs from '../views/Blogs.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, // Added our new route file named profile.vue { path: '/blogs', name: 'Blogs', component: Blogs } ] // Create Vue Router Object const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
To run our app, we’ll add a router to our App.vue
file as follows:
// App.vue <template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | <router-link to="/blogs">Blogs</router-link> </div> <router-view/> </div> </template> <script> export default { name: 'App', } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; margin-top: 60px; } #nav { font-size: 1.25rem; margin: 2rem; } </style>
If you head over to http://localhost:8080/
, you’ll see two routes that will open the homepage and the blog page.
Routing using static routes is fairly straightforward when your app is simple, however, realistically, your project will be more complex than just a homepage and blog page.
For example, let’s say that our blog has 100 posts, each with a unique URL. Creating a new component for each blog post and individually adding a path simply isn’t a feasible option.
Instead, we can add dynamic routing in our application. First, let’s create a new Post
component, which will serve as a template for displaying each unique blog:
// /views/Post.vue <template> <div> <h1> Welcome to Post page </h1> <p>This is the page that opens on <strong>/blog/{{ $route.params.id }}</strong> route</p> </div> </template>
Update the router/index.js
file with the new route in the routes
array. Remember to include the import for the Post
component.
In the code below, we use :id
as a dynamic value in the route:
{ path: '/post/:id', name: 'Post', component: Post, }
Restart your app and head to localhost:8080/post/dynamic-routing
in your browser. You should see the post
page with the exact route above.
Now, when you add a new post to your blog page, the Post
component creates a template for the URL, simplifying it and using :id
as a dynamic value. We can programmatically pass any ID, and a single route will handle all of these requests.
Now that we’ve used dynamic routes to define the base structure of our blog, we can use nested routes, which combine multiple routes into a specific hierarchy, to define additional features related to the blog.
For example, suppose that we have a basic route defined for authors example.com/author
. Within author
, we nested the following pages for individual authors:
example.com/author/mohit
example.com/author/john
To look up all of the posts written by an individual author, we’ll nest down by one more level on the hierarchy and create a nested route that follows a structure similar to /author/mohit/posts
.
First, add another element to the routes
array. Inside the object that contains all the subroutes for this route, we’ll add a children
field:
{ path: '/author/:id', name: 'Author', component: Author, children: [ { path: 'posts', component: AuthorPosts, } ] }
URL redirection, also known as URL forwarding, is a technique that we can use to make a single webpage available from more than one address. Essentially, when a user attempts to open a URL that has been redirected, the browser opens the URL to which the redirection was made. URL redirection is good practice for privacy protection and preventing broken links when pages are moved.
To redirect a URL, we can add the redirect
attribute in the route
object. For example, suppose that we want to search for a post based on the name of the article. We can use query parameters to redirect it to a similar route:
{ // /search/postName -> /search?q=postName path: '/search/:postName', redirect: to => { return { path: '/search', query: { q: to.params.postName } } }, }
An alias is another term for accessing a particular URL. For example, if we want the site mohitkhare.com
to be reachable if a user types www.mohitkhare.com
, we can add an alias to the mohitkhare.com
domain. In this case, mohitkhare.com
is the parent site of the www.mohitkhare.com
alias.
We can also add an alias to routes using the alias
attribute. Continuing with our example, let’s say that we want to add an alias for the blogs
route. Whenever a user goes to the posts
route, they’ll see the same content that is on the blog page:
{ path: '/blogs', name: 'Blogs', component: Blogs, alias: '/posts' }
In this tutorial, we explored adding static and dynamic routes to our Vue.js application using Vue Router. We also learned how to improve and customize our routes by adding nested routes, URL redirection, and aliases.
With dynamic routing, we can send dynamic data through our routes, allowing us to simplify long, indecipherable URLs and classify webpages into nested hierarchies. Vue Router includes many other great features, like named routes and route transitions. I hope you enjoyed this tutorial!
Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps, including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.
The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error and what state the application was in when an issue occurred.
Modernize how you debug your Vue apps — start monitoring for free.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowThe useReducer React Hook is a good alternative to tools like Redux, Recoil, or MobX.
Node.js v22.5.0 introduced a native SQLite module, which is is similar to what other JavaScript runtimes like Deno and Bun already have.
Understanding and supporting pinch, text, and browser zoom significantly enhances the user experience. Let’s explore a few ways to do so.
Playwright is a popular framework for automating and testing web applications across multiple browsers in JavaScript, Python, Java, and C#. […]