vue技术栈

vue-router路由拦截器

2019-03-13  本文已影响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')
        }
      },
    }
  ]
})
上一篇 下一篇

猜你喜欢

热点阅读