Vue Router Patterns Chapter 20
- Trigger global beforeResolve hooks:
Providing in-component guards and async route components have been
resolved, we can now hook into the global router.beforeResolve method that
allows us to perform action(s) at this stage. - Navigation:
All prior Navigation Guards have been fired, and the user is now successfully
navigated to a route. - Trigger afterEach hooks:
Although the user has been navigated to the route, it doesn't stop there. Next, the
router triggers a global afterEach hook that has access to the to and from
parameters. As the route has already been resolved at this stage, it doesn't have
the next parameter and thus cannot affect navigation. - Trigger DOM updates:
Routes have been resolved, and Vue can appropriately trigger DOM updates. - Trigger callbacks within next in beforeRouteEnter:
As beforeRouteEnter does not have access to the component's this context,
the next parameter takes a callback that resolves to the component instance on
navigation. An example can be seen here:
beforeRouteEnter (to, from, next) {
next(comp => {
// 'comp' inside this closure is equal to the component instance
})
Programmatic navigation
We're not limited to template navigation using router-link; we can also
programmatically navigate the user to different routes from within our JavaScript. Inside of
our App.vue, let's expose the
button that will navigate them to either the /hello or /hello/:name route:
<template>
<div id="app">
<nav>
<button @click="navigateToRoute('/hello')">/Hello</button>
<button
@click="navigateToRoute('/hello/Paul')">/Hello/Name</button>
</nav>
<router-view></router-view>
</div>
</template>