创建一个全局注册的守卫

const router = new Router({...})
router.beforeEach((to, from, next) => {
    // ...
})
1
2
3
4

每一个守卫接收的三个参数

  1. to: 即将要进入的目标 路由对象
  2. from: 当前导航正要离开的路由
  3. next: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
    • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
    • next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
    • next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。
    • next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

代码展示

router文件夹下 放了两个文件 index.js 和 routes.js

index.js

import Vue from 'vue'
import Router from 'vue-router'
import store from 'store'
import { routers } from './router'
Vue.use(Router)

// 路由器配置
const RouterConfig = {
  routes: routers
}

// 把路由暴露出去
export const router = new Router(RouterConfig)

// 声明一个白名单列表, 作为判断页面使用
const whiteList = ['/login', '/404']

// 路由守卫
router.beforeEach((to, from, next) => {
    // NProgress.start() // 进度条
    // 判断vuex里面是否有token -- 使用vuex来判断是否登录过比较好 vuex就是vue的状态保持仓库 store里面的内容
    if(store.getters.token) { // 判断到vuex里面有保持到token
        if(to.path === '/login' || ...) { // 判断是否是登录页面或者其他一些登录之前操作的页面(例如:注册页面) 如果是不用再做登录直接跳转的主页面
            next({path: '/index'})
        }else {
            next()
        }
    }else { // 判断到vuex里面没有保持到token
        if(whiteList.indexOf(to.path) !== -1) { // array.indexOf()方法返回在该数组中第一个找到的元素位置,如果它不存在则返回-1。
            // 判断现有页面里面如果包含白名单的 就跳转页面
            next()
        }else { // 判断跳转页面不是白名单里面的就跳转登录页面做登录
            next({path : '/login'})
            // NProgress.done()
        }
    }
}


router.afterEach(_ => {
  window.scrollTo(0, 0)
  // NProgress.done()
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

routes.js

export const routers = [
    {
        path: '/login',
        component: () => import('views/login/index'),
        name: '登录',
        
        .....
    }
    
    .....
]
1
2
3
4
5
6
7
8
9
10
11

TOC