vue-router导航守卫(简单使用)

导航守卫

// 进入前守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  next()
})
// 进入后守卫
router.afterEach((to) => {
  NProgress.done()
  document.title = to.meta.title
})

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() 注册过的回调。

完整代码:

import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '@/views/login/login'
import Home from '@/views/home/home'

import Chart from '@/views/home/chart/chart.vue'
import Business from '@/views/home/business/business.vue'
import Question from '@/views/home/question/question.vue'
import Subject from '@/views/home/subject/subject.vue'
import UserList from '@/views/home/userList/userList.vue'
// 路由导航守卫
// 进入前守卫
// 导入nprogress   start()开启    done()结束
import NProgress from 'nprogress'
// 导入nprogress对应css
import 'nprogress/nprogress.css'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Login,
      meta: {
        title: '登录'
      }
    },
    {
      path: '/home',
      redirect: '/home/subject',
      component: Home,
      children: [
        {
          path: 'chart',
          component: Chart,
          meta: {
            title: '数据概览'
          }
        },
        {
          path: 'business',
          component: Business,
          meta: {
            title: '企业列表'
          }
        },
        {
          path: 'question',
          component: Question,
          meta: {
            title: '题库列表'
          }
        },
        {
          path: 'subject',
          component: Subject,
          meta: {
            title: '学科列表'
          }
        },
        {
          path: 'userList',
          component: UserList,
          meta: {
            title: '用户列表'
          }
        }
      ]
    }
  ]
})
// 导航守卫
// 进入前守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  next()
})
// 进入后守卫
router.afterEach((to) => {
  NProgress.done()
  document.title = to.meta.title
})

export default router
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值