Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Vue Router Patterns Chapter 20

Component Navigation Guards


How do we fix the lifecycle hook problem? In this instance, we can use what's known as a
Navigation Guard. This allows us to hook into different lifecycles of the router, such as the


beforeRouteEnter, beforeRouteUpdate, and beforeRouteLeave methods.


beforeRouteUpdate

Let's use the beforeRouteUpdate method to access information about the route change:


const HelloName = {
props: ['name'],
template: `<h1>Hello {{ name }}</h1>`,
beforeRouteUpdate(to, from, next) {
console.log(to);
console.log(from);
console.log(`Hello ${to.params.name}`)
},
}

If we check the JavaScript console after navigating to a different route under


/hello/{name}, we'll be able to see which route the user is going to and where they are


coming from. The to and from objects also give us access to params, queries, the full path,


and much more.


While we correctly get the log statements, if we try and navigate between routes, you'll note


that our application doesn't update with the parameter name prop. This is because we


haven't used the next function after we've finished doing any computations within the


guard. Let's add that in:


beforeRouteUpdate(to, from, next) {
console.log(to);
console.log(from);
console.log(`Hello ${to.params.name}`)
next();
},
Free download pdf