Vue || How To Create A 404 Not Found Route With Dynamic Nested Routes With Vue Router Using Vue

Print Friendly, PDF & Email

The following is a module which demonstrates how to create a 404 not found route with dynamic nested routes via Vue Router using Vue.

Routes can be checked using Navigation Guards. This page will demonstrate verifying nested routes using the Per Route Guard.

This will demonstrate how to create a route that catches all non existing routes with Vue Router. It will also demonstrate how to use navigation guards to make sure nested dynamic routes exists.

Note: The examples below assumes your project is already set up and configured. For an overview on how to get started with Vue and Vue Router, visit the official documentation.


1. Router Index File

The example below is a sample router index.js file. This file sets up the routes in the project.

There are 4 routes: a ‘Home‘ page, a ‘DestinationDetails‘ page, a ‘ExperienceDetails‘ page, and a ‘NotFound‘ page.

The ‘ExperienceDetails‘ page is a nested child route.

The DestinationDetails route is a dynamic route that accepts props. In this example, the route.params will be set as the component props. In this component, the ‘slug‘ prop is used as the dynamic route path identifier.

The ExperienceDetails nested child route is also a dynamic route. In this component, the ‘experienceSlug‘ prop is used as the dynamic route path identifier.

Using the beforeEnter navigation guard, we can check if the route is valid by checking the dynamic route path identifier. If the route is not valid, the ‘NotFound‘ route is navigated to.

The NotFound route catches all non existing routes.


2. Home Page

The example below is the ‘Home‘ route page. This demonstrates how to navigate to the DestinationDetails route using the dynamic props.

It uses router-link to navigate to the specific route.


3. Destination Details Page

The example below is the ‘DestinationDetails‘ route page. This demonstrates how to display information about the destination and navigate to the ExperienceDetails route using the dynamic props passed to it.

It uses router-link to navigate to the specific route, and uses router-view to display the nested content from the navigated child route.

When calling the child component, it will automatically receive the parent ‘slug‘ dynamic route path identifier as a parameter.


4. Experience Details Page

The example below is the ‘ExperienceDetails‘ route page. This demonstrates how to display information about the destination experience using the dynamic props passed to it.


5. Not Found (404) Page

The example below is the ‘NotFound‘ route page. This page catches all non existing routes.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Was this article helpful?
👍 YesNo

Leave a Reply