Handling dynamic routing and route parameters in Vue Router is a common requirement in Vue development, primarily involving two aspects: defining dynamic routes and accessing route parameters. I will elaborate on these aspects separately with examples.
1. Defining Dynamic Routes
Dynamic routing is primarily used to match a set of URLs with similar structures but varying specific values. In Vue Router, we define a dynamic segment by using a colon : followed by a name in the path. For example:
javascriptconst router = new VueRouter({ routes: [ // Dynamic path parameters start with a colon { path: '/user/:id', component: User } ] })
In this example, :id is a dynamic route parameter that matches paths like /user/1, /user/2, etc., and each path renders the same User component.
2. Accessing Route Parameters
After defining dynamic routes, we need to access these parameters within components. Vue Router provides several methods for this:
Accessing via this.$route.params
Within a Vue component, we can retrieve dynamic parameters using the this.$route.params object. For example, continuing with the User component:
javascriptexport default { data() { return { userId: null } }, created() { this.userId = this.$route.params.id; } }
When the route changes and the component is reused (i.e., only parameters vary), use watch to monitor route updates:
javascriptwatch: { '$route' (to, from) { this.userId = to.params.id; } }
Using the Route's props Option
Vue Router allows mapping route parameters directly to component props, simplifying parameter usage without extracting from $route. Modify the route definition as follows:
javascriptconst router = new VueRouter({ routes: [ { path: '/user/:id', component: User, props: true } ] })
Within the User component, use route parameters as props:
javascriptexport default { props: ['id'] }
This approach enhances component reusability and testability, as it avoids dependency on the global route object.
By employing these two primary methods, we can effectively manage dynamic routing and route parameters in Vue Router. This is particularly valuable for applications like user profile pages or product detail pages that display content based on URL changes.