vue-router 提供的导航钩子主要用来拦截导航,让它完成跳转或取消。vue
router.beforeEach 注册一个全局的 before 钩子:vue-router
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
每一个钩子方法接收三个参数:浏览器
to: Route: 即将要进入的目标 路由对象app
from: Route: 当前导航正要离开的路由函数
next: Function: 必定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
next(): 进行管道中的下一个钩子。若是所有钩子执行完了,则导航的状态就是 confirmed (确认的)。
next(false): 中断当前的导航。若是浏览器的 URL 改变了(多是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
next('/') 或者 next({ path: '/' }): 跳转到一个不一样的地址。当前的导航被中断,而后进行一个新的导航。eslint
2.afterEach同理,只是不用传入next函数code
const router = new VueRouter({ base: __dirname, routes }); new Vue({ // eslint-disable-line el: '#app', render: h => h(App), router }); let indexScrollTop = 0; router.beforeEach((route, redirect, next) => { if (route.path !== '/') { indexScrollTop = document.body.scrollTop; } document.title = route.meta.title || document.title; next(); }); router.afterEach(route => { if (route.path !== '/') { document.body.scrollTop = 0; } else { Vue.nextTick(() => { document.body.scrollTop = indexScrollTop; }); } })