Vue_Router_守卫

路由守卫:路由进行权限控制。

分为:全局守卫,独享守卫,组件内守卫。

全局守卫

//创建并暴露 路由器
const router=new Vrouter({
    mode:"hash"//"hash路径出现#但是兼容性强,history没有#兼容性差"
    routes:[
        {
            name:'banji',//命名路由,:to="{name='banji'}"
            path:'/class',  //当路径是 /class时,内容区就显示ClassPage这个组件。
            component:ClassPage,//上面的引用
			meta:{title:'信息'}//{}中自定义信息
        },
        {
            path:'/student',
            component:StudentPage,
			children:[//嵌套路由
			  {
				name:'banji',
                path:'/class',
                component:ClassPage,
			    meta:{title:'信息'}
			  }
			]
        }
    ]
});
//暴露之前添加守卫

//全局的路由前置守卫,处理可否去到目标组件。to,form 都有详细的【去来】信息
router.beforeEach((to,from,next)=>{
     //to:去哪,
	 //from:从哪来
	 document.title=from.meta.title;//读信息
	 //next()//放行,让不让跳转
})

//全局的路由后置守卫,处理到达组件之后的操作
router.afterEach((to,from)=>{
     //to:去哪,
	 //from:从哪来
})

//暴露路由
export default router;

独享守卫

//创建并暴露 路由器
const router=new Vrouter({
    routes:[
        {
            path:'/student',
            component:StudentPage,
			children:[//嵌套路由
			  {
				....
			  }
			],
			beforeEnter:(to,from,next)=>{...}//****独享路由守卫,里面与全局一样
        }
    ]
});
//暴露路由
export default router;

组件内守卫

//组件里面的路由守卫
export default {
     name:'组件名',
     data(){
         return{属性:值}
     },
     props:['参数'],
	 //***进入组件时的守卫,通过路由规则进入的,作用有点类似全局守卫。to,form 都有详细的【去来】信息
	 router.beforeEach((to,from,next)=>{
		 //to:去哪,
		 //from:从哪来
		 document.title=from.meta.title;//读信息
		 //next()允许进来
	 })

	 //离开组件时的守卫,处理到达组件之后的操作
	 router.afterEach((to,from,next)=>{
		 //to:去哪,
		 //from:从哪来
		 //next()允许出去
	 })
}

Vue_Router_守卫_第1张图片

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