Navigation guards provided by Vue Router are primarily used to guard navigations, either by redirecting the route or by canceling the navigation altogether. There are a number of ways to hook into the route navigation process, globally, per route, or even in component. In the last lesson, we discovered an issue with navigation to a destination that does not exist. Let's use a per route navigation guard on our destination page to fix this issue.
In this case, we want to use the before enter guard. This guard receives a to argument and a from argument. The to argument refers to the route that is being navigated to. The from argument refers to the route being navigated away from.
What we want to do here is check to see if the location specified in the param exists as a location in our data. If it does, we'll allow our route to go ahead and show the destination it's meant to show. But if it is not, we need to go to the Not Found page. Since we'll need to look through our data, let's go ahead and import it.
In our before enter function, we can use the find method, which returns the value of the first element in the array that satisfies the provided testing function. json and find the destination where the destination's ID is equal to the ID, which is the params ID of where the route is going to. If we don't find the destination, we'll return another route to redirect to. That is the not found route.
If the destination is found, everything will just continue on as it was. Now, if we go to our application and click on Brazil, and change the ID in the URL to thirty-three and the slug to Mexico. You will see that we go to the not found page. Perfect.
You'll also notice though that the URL changed and no longer reflects the URL of the page that we were trying to visit. It's better to just show the not found page, but keep the URL the same. We can do that by returning the route record with the name not found, but with the other info the same as the current page. Great.
In this lesson, we've used a per-route navigation guard. In-component and global navigation guards follow the same premise, but are just applied at a different level. Stick around for the route metafields lesson, where we'll be using a global navigation guard, and for the router and the composition API lesson, where we'll use a component-level navigation guard.