# 1 12.全局路由拦截实现登录判断

> [导航守卫 | Vue Router](https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E5%85%A8%E5%B1%80%E5%89%8D%E7%BD%AE%E5%AE%88%E5%8D%AB)

* #### 全局前置守卫

> 继承上章节内容,创建文件permission.js

```js
// src/permission.js

import router  from './router'
import { getToken } from '~/composables/auth'
import { toast } from '~/composables/util'


// 全局前置守卫
router.beforeEach((to, from, next) => {
    const token = getToken()
    
    // 没有登录，强制跳转到登录页面
    if(!token && to.path != '/login') {
        toast('请先登录', 'error')
        return next({ path: "/login"})
    }


    // 防止重复登录
    if(token && to.path == '/login'){
        return next({ path: from.path ? from.path: '/'})
    }
    next()
  })
```

* #### 添加到入口文件

  > main.js

```js
// main.js
import './permission'
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/centos/vue/xiang-mu/1-12.-quan-ju-lu-you-lan-jie-shi-xian-deng-lu-pan-duan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
