如何配置路由守卫

前言

    路由守卫,又叫导航守卫:就是路由跳转过程中的一些钩子函数。路由跳转是一个大的过程,这个大的过程分为跳转前中后等等细小的过程,在每一个过程中都有一函数,这个函数能让你操作一些其他的事儿的时机,这就是导航守卫。
vue中路由守卫一共有三种:全局路由守卫组件内路由守卫router独享守卫


路由守卫的配置基本相同 

一、 全局路由守卫

//  先在router的index.js中,使用VueRouter

Vue.use(VueRouter)

//  在路由的路径中,可以设置meta,以便进行一些守卫的判断,比如:
const routes = [
  {
    path: '/index',
    component: Index,
    meta: {
        needLogin: true
    }
  }
]

//  然后实例化VueRouter

const router = new VueRouter({
  // 是否设为哈希模式  hash  history
  // mode: 'history',
  // 配置基路径
  base: process.env.BASE_URL,  // process.env是node.js的一种环境对象
  // 守卫的范围
  routes
})

//  接着   to 表示去哪的路由  from表示从哪来的路由  next表示一个回调函数
//  next()//直接进to 所指路由
//  next(false) //中断当前路由
//  next('route') //跳转指定路由
//  next('error') //跳转错误路由

router.beforeEach((to, from,next) => {
  //  判断是否需要守卫
  if (to.meta.needLogin){
    //  通过请求即时判断登陆状态
    myinfo().then(res=>{
      //  登陆了
      if (res.data.code==0){
        //  直接放行
        next()
      }else {
        //  没登陆 弹框提示 并跳转到登录、注册页面
        Dialog.alert({
          message: '请先登录',
        }).then(() => {
          // on close
        });
        next('/login')
      }
    })
  }else {
    next()
  }
})

 二、组件间路由

//  跟methods: {}  等同级别书写   

//  在路由进入之前,组件实例还未渲染,所以无法获取this实例,只能通过vm来访问组件实例
beforeRouteEnter (to, from, next) {
  next(
    vm => {}
  )
}

//  同一页面,刷新不同数据时调用
beforeRouteUpdate (to, from, next) {
  next(
    vm => {}
  )
} 

//  离开当前路由页面时调用
beforeRouteLeave (to, from, next) {
  next(
    vm => {}
  )
}

 三、router独享守卫

//  直接在routes中的路由里

const routes = [
  {
    path: '/index',
    component: Index,
    beforeEnter: (to, from, next) => {
        next()
    }
  }
]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值