In Vue Router, we can mark a parameter as optional by adding a question mark ? to the route path. This means the parameter is not required; users can access the route without this parameter or provide it to access the same route with slightly different results or data.
Creating Routes with Optional Parameters
Suppose we have a Vue application with a user profile page where the user ID is optional. If a user ID is provided, we display the specific user's profile; otherwise, we display the current logged-in user's profile. In Vue Router configuration, we can set up the route as follows:
javascriptconst router = new VueRouter({ routes: [ { path: '/profile/:userId?', component: UserProfile } ] })
In the above route definition, :userId is a dynamic parameter, and ? indicates that this parameter is optional. This means both /profile and /profile/123 are valid routes that lead to the UserProfile component.
Using Optional Parameters in Components
In the UserProfile component, we can access the userId parameter via this.$route.params.userId. Based on whether userId is provided, we can decide to load the current logged-in user's profile or a specific user's profile.
For example:
javascriptexport default { data() { return { userProfile: null } }, created() { this.fetchUserProfile(); }, methods: { fetchUserProfile() { const userId = this.$route.params.userId || 'current user ID'; // Assume there is a fetchUser function that handles API requests fetchUser(userId).then(data => { this.userProfile = data; }); } } }
Summary
By using optional parameters in Vue Router, we can create more flexible routing strategies while leveraging the same component to handle various similar cases, thereby simplifying project structure and improving code reusability. In actual development, this technique is very useful, especially when displaying different data based on URL changes.