vue 页面鉴权 导航守卫beforeEach

导航守卫

导航守卫文档

使用 在创建router实例的地方
全局守卫
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
const router = new VueRouter({
    mode:'history', // 路由模式 hash history abstract
    routes:[
		{
			path:'/index',
			name:'index',
			component:()=>import('@/components/Head'),
			meta:{ // 元数据(描述数据的数据)
				title:'index'
			}
		}
	]
})

// 前置守卫:路由跳转之前
// to 要进入的路由
// from 从那个路由过来的
router.beforeEach((to, form, next)=>{
    /* 必须调用 `next` */
    // 动态修改网页标题
	document.title = to.matched[0].meta.title
    next()
})

// 全局解析守卫: 同时在所有组件内守卫和异步路由组件被解析之后 和beforeEach区别是在导航被确认之前
router.beforeResolve((to, form, next)=>{
    /* 必须调用 `next` */


    next()
})

// 后置守卫:路由跳转之后
router.afterEach((to, form)=>{
   
})

export default router 
next
next()// 直接进to 所指路由
next(false) // 中断当前路由
next('/route') // 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航
next({name:"route"})
next(error) // next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调

next(new Error('错误内容'))
router.onError((e)=>{
    console.log('xxx',e)
})
路由独享的守卫
const router = new VueRouter({
    mode:'history', // 路由模式 hash history abstract
    routes:[
		{
			path:'/index',
			name:'index',
			component:()=>import('@/components/Head'),
			meta:{ // 元数据(描述数据的数据)
				title:'index'
			},
			beforeEnter:(to, from, next) => {
				console.log("--about-beforeEnter--")
                next()
			}
		}
	]
})
组件内的守卫
// 组件对象
{
	template:'xxx',
	beforeRouteEnter(to, from, next) {
      // 在渲染该组件的时候调用 不能获取组件实例this
      console.log('---beforeRouteEnter-渲染该路由---')
      next()
		
	  // beforeRouteEnter 是支持给 next 传递回调的唯一守卫
	  next(vm => {
	     // 通过 `vm` 访问组件实例
	  })
    },
    beforeRouteUpdate(to, from, next) {
      // 在当前路由改变,但是该组件被复用时调用
      console.log('---beforeRouteUpdate-该组件被复用---')
      next()
    },
    beforeRouteLeave (to, from, next) {
      // 导航离开该组件的对应路由时调用
	
	  // 通常用来禁止用户在还未保存修改前突然离开
      console.log('---beforeRouteLeave-离开单前路由--')
      next()
    }
}
导航流程
触发导航 

当前路由离开守卫触发(失活的组件)  beforeRouteLeave

全局前置路由触发  beforeEach 

在重用的组件里调用 beforeRouteUpdata

路由独享的守卫(路由配置里调用) beforeEnter

解析异步路由组件

组件内的守卫 组件创建时触发(被激活的组件) beforeRouteEnter 

全局解析守卫触发 beforeResolve

导航被确认

全景后置路由 afterEach 

触发 DOM 更新

调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。

页面鉴权

在这里插入图片描述

// 鉴权页面路由
{
    path:"/userinfo",
    name:"userinfo",
    component:()=>import('@/views/Auth'),
    meta:{auth:true}
},

import store from '../store'
// 进入路由之前触发
// to 要进入的路由
// from 从那个路由过来的
router.beforeEach(function(to, from, next){
	 if(to.meta.auth){ //鉴权页面标记
	 	// 进入userinfo 要判断是否登录
	 	if(store.state.user.isLoading){ // 在登录中
	 		 // 携带参数path  如果有多个页面都需要登录验证
	 		 next({name:"Auth",query:{path:to.name}})  //跳转到鉴权页面
	 	}else if(store.state.user.islogin){ // 登录成功
	 		next() // 正常跳转
		}else{ // 没有登录 
			 next({name:"login"}) //跳转到登录页面
		}
	 	return 
	 }
     next()
})

鉴权页面

<template>
    <Center>
        <!-- auth 鉴权 -->
        验证中
    </Center>
</template>

<script>
import Center from '@/components/Center'
import {mapState} from 'vuex'
export default {
    components:{
        Center
    },
    computed:mapState('user',['data','isLogin','isLoading']),
    watch:{
        isLogin:{ // 监听登录状态变化
            immediate:true,
            handler(){
                this.handleLogin()
            }
        },
        isLoading:{
            immediate:true,
            handler(){
                this.handleLogin()
            }
        }
    },
    methods:{
        handleLogin(){
            if(this.isLoading) return // 是否在登录中
            if(this.isLogin){ // 是否在登录成功
              
                if(this.$route.query.path){
                	// 跳转this.$route.query.path 路径
                	this.$router.push({name:this.$route.query.path})
                }else{
                	// 没有指定页面路由 就跳转个人中心  
                	this.$router.push({name:'userinfo'})
                }
            }else{
                // 跳转登录页
                this.$router.push({name:'login'})
            }
        }
    }
}
</script>
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值