Creating Dynamic Routes in Your Vue.js App with Vue RouterThis tutorial will walk you through the process of creating dynamic routes step by step with Vue router and using vue navigation guards.

Dynamic routes may bring your Vue.js project to a new level of capability and engagement. By allowing users to travel to different pages based on dynamic criteria, you can build a more personalised and engaging user experience. In this guide, we'll walk you through adding dynamic routes to your app with Vue Router, offering step-by-step guidance to help you easily integrate this powerful feature.
Understanding Dynamic Routes in Vue.js
One of the most important features in Vue.js is dynamic routes, which build dynamic and personalized URLs for your application. Dynamic routes can generate content on your pages by passing parameters in the URL. It gives you options for personalization and interaction with your users.
This tutorial will show you what dynamic routing in Vue.js means and how it's implemented within an application.
Setting Up Dynamic Routes in Your Vue.js App with Vue Router
Before you can generate dynamic routes in your Vue.js project, you must install and configure Vue Router.
Ensure that the Vue Router is installed in your project. You can do this by typing npm install vue-router
into your terminal. After installing the Vue Router, you must import it into your main.js
file and utilise it as a plugin. This allows you to access the router functionality from anywhere in your app.
import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
routes: [], // Your routes will be defined here
});
new Vue({
el: '#app',
router,
render: h => h(App),
});
Next, you must define your routes. This is done by creating an array of route objects in your router.js
file, each representing a separate route in your project.
Each route object should have a path property that describes the URL for that route and a component property that indicates which component should be rendered when that route is requested.
Additional features, such as metadata or dynamic parameters, can be added to your route objects. After you've defined your routes, you'll need to build a router instance and pass your routes as a configuration option.
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: UserProfile },
],
});
In this example, :id
is a route parameter with any value. When the route matches, the value of :id
can be accessed within your component using this.$route.params.id
.
Add the component to your main App.vue
file to mount the router instance to your app. After completing these steps, you can construct dynamic routes in your Vue.js project.
Creating Dynamic Route Components with Vue Router
After completing the configuration for dynamic routes in your Vue.js project, you can begin building the route components. You'll need to develop a new Vue component for each dynamic route you want to construct. You can define the route's behaviour and content within each component.
To create a dynamic route component, import the required dependencies at the top of your code. This contains Vue and any other components or libraries you may need. Next, create your component's template to control how it is rendered on the page. You can utilise HTML, CSS, and Vue directives to achieve the necessary layout and functionality.
After you've defined your template, you can add any necessary data, methods, or calculated properties to your component. This enables you to dynamically adjust your component's content or behaviour based on user interactions or other factors.
You must export your component for your router setup. This is usually accomplished by adding a line of code at the bottom of your project that says something like "export default MyComponent".
You can now add your dynamic route component to your router setup. Locate the route object corresponding to the dynamic route you wish to create in your router.js
file. Replace the component property with the name of your newly formed component. You may also add any necessary attributes or parameters to the route object.
Once you've finished these steps for each dynamic route you want to construct, you can save your files and test your app. When a user navigates to one of your dynamic routes, the relevant component is generated, displaying the content and functionality you specify.
<template>
<div>
<h1>User Profile</h1>
User ID: {{ $route.params.id }}
</div>
</template>
<script>
export default {
name: 'UserProfile',
};
</script>
Passing Parameters to Dynamic Routes with Vue Router
You can send parameters to dynamic routes in your Vue.js project and generate them. This enables you to tailor the content or behaviour of your components to specific parameters.
You can use the colon syntax in your route setup to pass arguments to a dynamic route. For example, if you have a dynamic route for specific blog articles, you can declare it as "/user/:id". The $route.params
object may then be used to access the "id" argument in your component. Using computed properties or methods to dynamically adjust your component's content or behaviour based on the parameter value.
Optional Parameters
You can also define optional route parameters by using the ?
modifier.
const router = new VueRouter({
routes: [
{ path: '/user/:id?', component: UserProfile },
],
});
In this case, the id parameter is optional, and the route will match both /user
and /user/123
.
Catch-All Parameters
You can define catch-all routes using an asterisk (*). These routes match any path not matched by previous routes. For example:
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: UserProfile },
{ path: '*', component: NotFound },
],
});
In this example, the NotFound
component will be displayed for any route that doesn't match the /user/:id
pattern.
Handling Dynamic Route Changes and Navigation Guards
To provide a good user experience while working with dynamic routes in your Vue.js app, handling route changes and correctly creating navigation guards is important.
Using beforeRouteUpdate to Fetch Data
You can use the beforeRouteUpdate
hook in your component to manage dynamic route changes. This hook is triggered anytime the route parameters change, allowing you to acquire fresh data or make necessary changes.
For example, if you have a dynamic route for individual blog articles, you can use your component's "beforeRouteUpdate" hook to fetch the updated blog post content. When the user navigates between different blog articles, the content is always up to date.
<template>
<div>
<h1>{{ item.name }}</h1>
<!-- Display the fetched data -->
</div>
</template>
<script>
import { ref, onBeforeRouteUpdate } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
export default {
setup() {
const item = ref({});
const route = useRoute();
const fetchData = () => {
const itemId = route.params.itemId;
// Make an API request to fetch data based on itemId
//example using Axios
axios.get(`/api/items/${itemId}`)
.then((response) => {
item.value = response.data;
})
.catch((error) => {
// Handle the error
console.error(error);
});
};
// Fetch data when the route updates
onBeforeRouteUpdate((to, from, next) => {
fetchData();
next();
});
// Initial data fetch when the component is created
fetchData();
return {
item,
};
},
};
</script>
Using beforeEnter To Check If User Can Access Page
In addition to dealing with dynamic route changes, navigation guards can be used to restrict access to specific routes. Before going to a route, navigation guards allow you to execute checks, such as determining whether the user is authenticated or certain conditions are met.
For example, before giving access to a protected route, you can use the "beforeEnter" navigation guard to check if the user is signed in. If not, you can send the user to a login page or display an error message.
// router.js
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{
path: '/public',
name: 'public',
component: () => import('./views/Public.vue'),
},
{
path: '/private',
name: 'private',
component: () => import('./views/Private.vue'),
beforeEnter: (to, from, next) => {
// Add your access control logic here
const isAuthenticated = /* Your authentication check */;
if (isAuthenticated) {
next(); // Allow access
} else {
next('/login'); // Redirect to login or another route
}
},
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
Programmatic Navigation Using Vue Router
You can navigate to dynamic routes programmatically using this.$router.push
or this.$router.replace
. For example, this will redirect the user to a new page:
// Inside a method or event handler
this.$router.push({ path: '/user/123' });
Handling dynamic route changes and using navigation guards can ensure that your Vue.js app provides a smooth and secure user experience. This approach will help you learn dynamic routes and create a robust user interface, whether constructing a simple blog or a major web application.