Permission verification file for vue2.x project from 0 to 1 (6)

General permission verification files will be placed in the folder under utils under src. I named it  permission.js. You can change the name to anything + .js , but the name of enterprise-level projects must be understood by others. You will get scolded!

 

 1. After first creating  the permission.js (hereinafter collectively referred to as the permission verification file)  file,

 2. Secondly, we need to introduce it globally

  Introduced in the main.js file

import "@/utils/permission.js"

3. Write the code for the permission verification file

import router from '@/router'
import store from '@/store'
import { Message  } from 'element-ui'

let whiteList = ["/userLogin"] // 白名单  在这个名单里的路由 没有token  可以进入

// 路由跳转之前
router.beforeEach((to, from, next) => {
    let path = from.path // 记录是从哪个路由跳转来的
    // 如果之前有页面跳转到登录 则记录该页面路由到vuex中
    if (path){
        store.commit('SET_JUMPROUTER', path)
    } else { // 否则跳转到用户页
        store.commit('SET_JUMPROUTER', "/")
    }
    // 获取token
    let token = localStorage.getItem("token")
    let isJump = false // 判断是否跳转
    // 修改项目名称
    if (to.meta.title) {
        document.title = to.meta.title
    }
    // 判断token  有就跳转
    if (token) {
        // 如果有token 则跳回到  跳转来时的页面
        next()
    } else {
        // 判断白名单中是否有值  否则forEach会报错
        if (whiteList.length) {
            whiteList.forEach((item) => {
                if (to.path == item) {
                    // 如果路由在白名单里 直接跳转
                    isJump = true // 如果跳转 则变为true
                    next() // 没有next函数 将不会跳转到新路由 
                }
            })
            if (!isJump) {
                // 没有token又不在白名单当中则跳转到登陆页
                Message.error('身份过期!')
                next("/userLogin")
            }
        } else {
            // 没有token白名单中没值当中则跳转到登陆页
            Message.error('身份过期!')
            next("/userLogin")
        }
    }
})

If you use my permission verification file, you also need to add it to vuex (index.js under the store folder under src). Different projects may have different locations and the writing may change slightly.

 Then modify the login page and login interface to where it jumps from. After logging in, it will jump to where it goes. If not, it will jump to the homepage by default.

Isn’t it very EZ!

Guess you like

Origin blog.csdn.net/notagoodwriter/article/details/129004530