vue-router路由守卫

概述

在我们使用vue-router的时候,路由守卫就像监听器、拦截器一样,帮我们做一些鉴权等操作,vue中的路由守卫分为全局路由守卫、独享路由守卫、组件内的路由守卫

全局路由守卫: beforeEach、 afterEach

组件独享路由守卫 :beforeEnter、 beforeLeave

组件内路由守卫:beforeRouteEnter、 beforeRouteUpdate、 beforeRouteLeave

以上的路由钩子足够见名知义,全局的为路由前置守卫和路由后置守卫,组件独享路由守卫进入时守卫和离开时守卫,组件内路由守卫是前置守卫、路由更新时守卫,和离开时的后置守卫,下面将一一介绍路由守卫

写路由守卫的位置:

全局路由守卫写在:main.js中或者router文件夹下的index.js中

组件独享路由守卫写在:router下的index.js中

组件内路由守卫写在:具体的组件之中.vue文件之中

全局路由守卫

前置路由守卫

首先需要在用到路由守卫的地方明确声明{isAuth:true}

    {
        path: '/',
        name: 'HomePage',
        component: () => import('../views/HomePage.vue'),
        meta: { isAuth: true, title:'主页' },
    },

 添加前置路由守卫

//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
    //如果路由需要跳转
    if (to.meta.isAuth) {
        //判断 如果localStorage本地存储是xxx的时候,可以进去
        if (localStorage.getItem('xxx') === 'xxx') {
            next()  //放行
        } else {
            // 或者定位到某个具体页面
            alert('抱歉,您无权限查看!')
        }
    } else {
        // 否则,放行
        next()
    }
})

后置路由守卫

前提是也需要在单个路由上加入meta信息,上边已经加过,可参考前置路由守卫中的meta信息,后置中没有next()

//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {
    document.title = to.meta.title || '默认名'    //修改网页的title
})

组件独享路由守卫

组件独享路由守卫是某一个路由所单独共享的守卫,组件独享路由守卫需要在路由信息中配置,组件独享路由守卫只有前置,没有后置,当然有离开时的钩子函数,这里不做赘述

    {
        path: '/',
        name: 'HomePage',
        component: () => import('../views/HomePage.vue'),
        meta: { isAuth: true },
        beforeEnter: (to, from, next) => {
            if (to.meta.isAuth) { 
                if (localStorage.getItem('xxx') === 'xxx') {
                    next()  //放行
                } else {
                    // 或者跳转某一指定路由
                    alert('抱歉,您无权限查看!')
                }
            } else {
                next()  //放行
            }
        }
    },

组件内路由守卫 

首先位置方面是写在组件内部的路由守卫,写在.vue文件之中

//通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next) {
  if(toString.meta.isAuth){
    if(localStorage.getTime('xxx')==='xxx'){
      next()
    }else{
      alert('无权限查看!')
    }
  } else{
    next()
  }
},
 
//通过路由规则,离开该组件时被调用 
beforeRouteLeave(to,from,next) {
 next()
}

你可能感兴趣的:(前端星球,vue.js,javascript,前端)