vue-router 导航钩子的具体使用方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue-router 导航钩子的具体使用方法

Lizzy0077   2020-05-16 我要评论

vue-router 提供的导航钩子主要用来拦截导航,让它完成跳转或取消。

全局钩子

1、router.beforeEach 注册一个全局的 before 钩子:

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
 // ...
})

每个钩子方法接收三个参数:

  • to: Route: 即将要进入的目标 路由对象
  • from: Route: 当前导航正要离开的路由
  • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 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 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们