美文网首页vue技术栈
vue-router路由拦截器

vue-router路由拦截器

作者: 曼木子 | 来源:发表于2019-03-13 21:44 被阅读57次

Vue Router 是vue.js官方路由管理器

路由出口

<router-view></router-view>

声明式导航

<router-link :to="...">
</router-link>

编程式导航

router.push(...)

全局前置守卫

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: [{
    path: '/',
    component: Home,
    children: [{
      path: 'home',
      name: 'index',
      component: index
    }, {
      path: 'foo',
      name: 'foo',
      beforeEnter: (to, from, next) => {
      // authkey 存在 进入该路由,不存在跳转到登陆页面
        if (sessionStorage.getItem('token')) {
          console.log(sessionStorage.getItem('token'))
          next()
        } else {
          next('/user/Login')
        }
      },
      meta: {
        requireAuth: true
      },
      component: personal
    }, {
      path: '',
      redirect: '/home'
    }
  }]
})
// 全局路由守卫
router.beforeEach((to, from, next) => {
  // 逻辑操作
})

全局后置钩子

const router = new VueRouter({ ... })
router.afterEach((to, from) => {
  // 逻辑操作
})

路由独享的守卫

const router = new VueRouter({
  routes: [
    {
      path: '/test',
      component: test,
      beforeEnter: (to, from, next) => {
      // authkey 存在 进入该路由,不存在跳转到登陆页面
        if (sessionStorage.getItem('authkey')) {
          console.log(sessionStorage.getItem('authkey'))
          next()
        } else {
          next('/user/Login')
        }
      },
    }
  ]
})
  • to: Route: 即将要进入的目标 路由对象
  • from: Route: 当前导航正要离开的路由
  • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
  • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
  • next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
  • next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: 'home' 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。
  • next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。
  • 确保要调用 next 方法,否则钩子就不会被 resolved。

相关文章

网友评论

    本文标题:vue-router路由拦截器

    本文链接:https://www.haomeiwen.com/subject/xohxmqtx.html