路由守卫的参数介绍
import Vue from "vue"; import VueRouter from "vue-router"; import Home from "../views/home.vue"; Vue.use(VueRouter); const routes = [ { path: "/", name: "Home", component: Home, }, { path: "/about", name: "About", component: () => import("../views/About.vue"), }, ] const router = new VueRouter({ mode: "history", base: process.env.BASE_URL, routes, }); // 这是一个全局前置路由,注意是全局的前置路由 // 在每一次切换路由之前,都会触发该函数注意是之前 // 它有三个参数, // to==>到哪一个路由,form==>来源哪一个路由,next是否允许前往某一个路由 //如果没有执行next页面将会值空白页面 router.beforeEach((to, form, next) => { console.log("在每一次切换路由之前,都会触发该函数") next() }) export default router;
权限就需要路由守卫
现在我们有一个需求,如果要进入就是richtext页面;
用户user等于必须等于admin。才能够进入
否者不能够就进入页面,并提示弹窗
let user='user' // to==>到哪一个路由, // form ==> 来源哪一个路由, // next是否允许前往某一个路由,如果没有执行next()这页面空白 router.beforeEach((to, form, next) => { console.log(' to',to); if (to.path == '/richtext') { if (user == 'admin') { next(); } else { alert('你不是管理员') } } else { next() } })
元路由meta
很多时候,我们需要将每一个路由上放置一个的信息
我们可以放在mata上
简单配置如下
path: "/zujian", name: "zujian", meta: { user: admin, info:'我是admin', key:'key-value的形式' }, component: () => import("../views/zujian.vue"), },
全局后置路由守卫
// 全局后置路由守卫,它只有两个参数 // to==>到哪一个路由, // form ==> 来源哪一个路由, router.afterEach((to,form) => { console.log('to', to, form); console.log('form',to,form); })
有的小伙伴可能会说,
这个后置路由守卫都切换到自己需要的页面了。
还守卫了毛线,靠!
你这样一说还真是的,我都切换完了。
还需要你守卫吗?你一遍凉快去吧。
难道它真的没有一点儿作用了吗?
不是的你说的那样,它是有作用的;
在动态更改系统顶部的标题的时候,
就需要使用这个全局后置路由守卫
router.afterEach((to,form) => { console.log('to', to); console.log('form', form); document.title=to.mata.title })
独享路由守卫
独享路由守卫:顾名思义就是对某一个路由进行守卫 { path: "/zujian", name: "zujian", component: () => import("../views/zujian.vue"), // 独享路由~注意:没有独享后置路由 //独享只有一个 beforEnter: (to, form,next) => { // to==>到哪一个路由, // form ==> 来源哪一个路由, // next 放行 } },
组件内路由守卫
<template> <div> 我是页面测试二 </div> </template> <script> export default { //通过路由规则进入该组件时候被调用 beforeRouteEnter (to, from, next) { console.log('beforeRouteEnter==>to',to, ); console.log( 'beforeRouteEnter==>from',from ); // 放行,如你你不放行,路由景无法进入该页面 // 在视图上页面显示的是上一个页面哈 next(); }, //通过路由规则,离开组件的时候被调用 beforeRouteLeave(to, from, next){ console.log('beforeRouteLeave==>',to ); console.log('beforeRouteLeave==>',from ); // 如果你不放行,路由无法离开该页面 // 在视图上始终显示该页面,因为路由没有离开 next(); } } </script>