The navigation hook provided by vue-router is mainly used to intercept navigation and allow it to complete jump or cancel.
Global hook
1. Register a global before hook:
const router = new VueRouter({ ... }) ((to, from, next) => { // ... })
Each hook method receives three parameters:
- to: Route: The target to be entered Routing object
- from: Route: The route that the current navigation is about to leave
- next: Function: Be sure to call this method to resolve the hook. The execution effect depends on the calling parameters of the next method.
next(): performs the next hook in the pipeline. If all hooks are executed, the navigation status is confirmed.
next(false): interrupts the current navigation. If the browser's URL has changed (maybe it's manual or the browser's back button), the URL address will be reset to the corresponding address from route.
next('/') or next({ path: '/' }): Jump to a different address. The current navigation is interrupted and a new navigation is performed.
Similarly, you don't need to pass in next function
Example: A single page application saves its browsing location on the homepage when returning to the homepage. And assign values to each page title
const router = new VueRouter({ base: __dirname, routes }); new Vue({ // eslint-disable-line el: '#app', render: h => h(App), router }); let indexScrollTop = 0; ((route, redirect, next) => { if ( !== '/') { indexScrollTop = ; } = || ; next(); }); (route => { if ( !== '/') { = 0; } else { (() => { = indexScrollTop; }); } })
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.