Dynamic routing in Vue Router allows you to create routes that can match patterns and extract parameters from the URL. This is particularly useful for applications that need to handle a variety of similar routes, such as user profiles, product pages, or any other resource that can be identified by a unique identifier.
Key Concepts
- Dynamic Segments: These are parts of the URL that can change and are represented by a colon (
:) followed by a parameter name. - Route Parameters: These are the values extracted from the dynamic segments of the URL.
- Accessing Route Parameters: You can access these parameters in your component to fetch data or perform other actions.
Setting Up Dynamic Routes
Defining Dynamic Routes
To define a dynamic route, you use a colon (:) followed by the parameter name in the path. For example, to create a route for user profiles, you might define a route like this:
In this example, :id is a dynamic segment that will match any value in that position of the URL.
Accessing Route Parameters
Once you have defined a dynamic route, you can access the route parameters in your component using the $route object. Here’s how you can do it:
export default {
name: 'UserProfile',
computed: {
userId() {
return this.$route.params.id;
}
},
created() {
this.fetchUserData();
},
methods: {
fetchUserData() {
const userId = this.userId;
// Fetch user data using the userId
}
}
};In this example, this.$route.params.id gives you access to the id parameter from the URL.
Practical Example
Let's create a simple example to demonstrate dynamic routing. We will create a user profile page that displays user information based on the user ID in the URL.
Step 1: Define the Route
First, define the dynamic route in your router configuration:
import Vue from 'vue';
import Router from 'vue-router';
import UserProfile from './components/UserProfile.vue';
Vue.use(Router);
const routes = [
{
path: '/user/:id',
component: UserProfile
}
];
const router = new Router({
routes
});
export default router;Step 2: Create the UserProfile Component
Next, create the UserProfile component that will display the user information:
<template>
<div>
<h1>User Profile</h1>
<p>User ID: {{ userId }}</p>
<!-- Display other user information here -->
</div>
</template>
<script>
export default {
name: 'UserProfile',
computed: {
userId() {
return this.$route.params.id;
}
},
created() {
this.fetchUserData();
},
methods: {
fetchUserData() {
const userId = this.userId;
// Fetch user data using the userId
console.log(`Fetching data for user ID: ${userId}`);
}
}
};
</script>Step 3: Test the Dynamic Route
Now, navigate to a URL like /user/123 in your application. You should see the user ID displayed on the profile page, and the fetchUserData method should log the user ID to the console.
Exercises
Exercise 1: Create a Product Page
- Define a dynamic route for a product page with the path
/product/:productId. - Create a
ProductPagecomponent that displays the product ID from the URL. - Access the product ID in the component and log it to the console.
Solution:
// router.js
import Vue from 'vue';
import Router from 'vue-router';
import ProductPage from './components/ProductPage.vue';
Vue.use(Router);
const routes = [
{
path: '/product/:productId',
component: ProductPage
}
];
const router = new Router({
routes
});
export default router;<!-- ProductPage.vue -->
<template>
<div>
<h1>Product Page</h1>
<p>Product ID: {{ productId }}</p>
</div>
</template>
<script>
export default {
name: 'ProductPage',
computed: {
productId() {
return this.$route.params.productId;
}
},
created() {
this.fetchProductData();
},
methods: {
fetchProductData() {
const productId = this.productId;
console.log(`Fetching data for product ID: ${productId}`);
}
}
};
</script>Common Mistakes and Tips
-
Mistake: Forgetting to define the dynamic segment in the route path.
- Tip: Always use a colon (
:) followed by the parameter name to define a dynamic segment.
- Tip: Always use a colon (
-
Mistake: Trying to access route parameters before the component is created.
- Tip: Use lifecycle hooks like
createdormountedto access route parameters after the component is initialized.
- Tip: Use lifecycle hooks like
Conclusion
Dynamic routing is a powerful feature in Vue Router that allows you to create flexible and dynamic routes. By using dynamic segments and accessing route parameters, you can build applications that respond to a variety of URL patterns. In the next section, we will explore nested routes and how to create more complex routing structures.
Vue.js Course
Module 1: Introduction to Vue.js
- What is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance
Module 2: Vue.js Basics
- Template Syntax
- Data Binding
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- Slots
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
Module 5: State Management with Vuex
- Introduction to Vuex
- State, Getters, Mutations, and Actions
- Modules in Vuex
- Using Vuex in Components
- Advanced Vuex Patterns
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
Module 9: Advanced Vue.js Concepts
- Render Functions and JSX
- Server-Side Rendering (SSR) with Nuxt.js
- Vue 3 Composition API
- Performance Optimization
