一..全局路由前置守卫
1.首先看一下文档结构
Dashboard和Login是一级页面 home about mine是在Dashboard下的二级页面
2.router.js代码如下
import Vue from 'vue' import Router from 'vue-router' // 一级界面 import Login from './views/Login' import DashBoard from './views/DashBoard' // 二级界面 import Home from './views/Home' import Mine from './views/Mine' const About = ()=> import('./views/About'); Vue.use(Router); const router = new Router({ routes: [ { path: '/', redirect: '/dashboard' }, { path: '/dashboard', name: 'dashboard', component: DashBoard, children: [ { path: '/dashboard', redirect: '/dashboard/home' }, {path: 'home', name: 'home', component: Home,}, {path: 'about', name: 'about', component: About}, {path: 'mine', name: 'mine', component: Mine} ], }, {path: '/login', name: 'login', component: Login} ] }); // 全局路由前置守卫 router.beforeEach((to, from, next)=>{ // console.log(to, from); if(to.path !== '/login'){ // 验证是否登录 if(window.isLogin){ // 已经登录 window.isLogin是自己自定义的一个全局变量 登录是 点击一下就是变为true next(); }else { // 没有登录 next('/login?redirect='+ to.path); // next('/login?redirect=/dashboard/mine'); //next('/login'); } }else { // 不需要验证 next(); } // 放行 next(); }); // 全局路由后置守卫 router.afterEach((to, from) => { // console.log('来了!'); }); //把router作为实例输出出去 export default router;
login.vue里面的代码
点击按钮window.isLogin = true就登录跳转,这里只是做了一个模拟登录
<template> <div> <h2>登录界面</h2> <button @click="login">登录</button> </div> </template> <script> export default { name: "Login", methods: { login(){ // 1. 登录成功 window.isLogin = true; // 2. 获取回调地址 const redirect = this.$route.query.redirect; if(redirect){ // 有回调地址 this.$router.push(redirect); }else { // 没有回调地址 // 去首页 this.$router.replace('/'); } } } } </script> <style scoped> </style>