vue-router 提供的导航钩子主要用来拦截导航,让它完成跳转或取消。
全局钩子
1、router.beforeEach 注册一个全局的 before 钩子:
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
每个钩子方法接收三个参数:
next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。
2.afterEach同理,只是不用传入next函数
示例:一个单页面应用,返回首页时,保存其在首页的浏览位置。并且给每一个页面title赋值
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; }); } })
Copyright © 2019- haog.cn 版权所有 赣ICP备2024042798号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务