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

2019-11-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;
  });
 }
})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • vue 和vue-touch 实现移动端左右导航效果(仿京东移动站导航)
  • vue2.0实现导航菜单切换效果
  • 非常实用的vue导航钩子
  • vue实现导航栏效果(选中状态刷新不消失)
  • vue router仿天猫底部导航栏功能
  • vue实现nav导航栏的方法
  • 详解使用Vue Router导航钩子与Vuex来实现后退状态保存
  • vue2.0 elementUI制作面包屑导航栏
  • VueRouter导航守卫用法详解
  • vue组件tabbar使用方法详解

《vue-router 导航钩子的具体使用方法.doc》

下载本文的Word格式文档,以方便收藏与打印。