文章目录
0.路由的概念1.路由守卫的定义定义官方解释路由守卫的分类钩子函数 2.路由守卫的使用场景3.语法:`router.beforeEach((to,from,next) => {}`4.路由守卫示例:(接前例)为点击Center路由的操作判断是否已登录router.index.jsviews/Login.vue结果0.路由的概念
路由其实是一种映射关系。
生活中的路由:设备和ip的映射关系;node.js路由:接口和服务的映射关系;(前端)Vue中的路由:路径和组件的映射关系。
1.路由守卫的定义
定义
路由守卫又称导航守卫,指是路由跳转前、跳转中、跳转后过程中的一些钩子函数。
官方解释
vue-router提供的导航守卫,要通过跳转或取消的方式来守卫导航。
路由守卫的分类
全局路由、组件内路由,路由独享。
钩子函数
1.全局路由的钩子函数有:beforeEach、beforeResolve、afterEach(参数中没有next)2.组件内路由的钩子函数有:beforeRouterEnter、beforeRouteUpdate、beforeRouteLeave3.路由独享的钩子函数有:beforeEnter
2.路由守卫的使用场景
给路由添加一个权限判断:路由跳转之前,会触发一个函数
场景:用户在登录的状态下就能去到某页面,但是未登录则给你弹出一个未登录的提示。
3.语法:router.beforeEach((to,from,next) => {}
let isLogin = false; //未登录router.beforeEach((to,from,next) => {//路由跳转“之前”先执行这里,决定是否跳转if (to.path === '/Login' && isLogin === false) {alert("请登录”)next(false) //阻止路由跳转}else {next() //正常放行}});
参数
to:要跳转到的路由目标from:从哪里跳转的路由 (路由对象信息)来源next:函数体 必须要next()才会让路由正常地跳转和切换
全局路由在真正跳转之前,会执行一次beforeEach函数,
next调用则跳转,也可以强制修改要跳转的路由。
4.路由守卫示例:(接前例)为点击Center路由的操作判断是否已登录
router.index.js
import vueRouter from "vue-router"// 引入路由...import Login from "@/views/Login"// 配置路由// 创建路由对象routerconst router = new vueRouter({routes: [...{path: "/Login",component: Login}],});//此处一般用token验证const checkUser = {isLogin() {return false;}};//登陆守卫router.beforeEach((to, from, next) => {console.log(to.path);//输出用户的点击路径if (to.path == "/Center") {//点击Center:登录状态检查console.log("正在检查登录状态...");;if (checkUser.isLogin()) {//是否已登录console.log("您已登陆!");next(); //登录:放行} else {console.log("您未登陆!正在跳转到登录页面...");next("/Login"); //未登录:跳转至Login页}} else {//点击别的页面:直接放行next();}});// 导出路由export default router;
views/Login.vue
<template><div>用户名:<input type="text">密码:<input type="password"></div></template>
结果
用户点击一次:个人中心
因没有登录而自动转到Login页面,
若已登录
const checkUser = {isLogin() {//return false;return true;}};
则放行进入Center.页面