vue 后台管理系统菜单权限管理

Easter79
• 阅读 763

来自:https://www.cnblogs.com/fqh123/p/11094296.html 侵删

login登录方法

login() {
      if (!this.username) {
        return this.$message.error("请输入用户名");
      }
      if (!this.password) {
        return this.$message.error("请输入密码");
      }
      if (this.checked) {
        localStorage.setItem("username", this.username);
        localStorage.setItem("password", this.password);
        localStorage.setItem("checked", 1);
      } else {
        localStorage.removeItem("username");
        localStorage.removeItem("password");
        localStorage.removeItem("token");
      }
      let data = {
        username: this.username,
        password: this.password
      };

      this.$store
        .dispatch("login", data)
        .then(() => {
          this.$message.success("登录成功");
          this.$router.push({ path: "/" });
        })
        .catch(() => {
          console.log(222);
          this.$message.error("登陆失败");
          //   this.loading = false;
        });
    },

store中

import Vue from "vue";
import Vuex from "vuex";
import { getToken, setToken, removeToken, deepClone } from '@/utils/auth'
import { formatDate } from "@/utils/index.js";
import { login, getUserInfo } from "@/api/mine.js";
import { asyncRouterMap, constantRoutes } from '@/router';

Vue.use(Vuex);

function hasPermission(menuMap, route) {
    if (route.meta && route.meta.menu_code) {
        for (const item of menuMap) {
            if (item === route.meta.menu_code) {
                return true
            }
        }
        return false
    } else {
        return true
    }
}
function filterAsyncRouter(asyncRouterMap, menuMap) {
    const accessedRouters = asyncRouterMap.filter(route => {
        if (hasPermission(menuMap, route)) {
            if (route.children && route.children.length) {
                route.children = filterAsyncRouter(route.children, menuMap)
            }
            return true
        }
        return false
    })
    return accessedRouters
}

const store = new Vuex.Store({
    state: {
        userId: '',
        mapcontrols: '', //地图的集合
        carlist: '', //行车的集合
        attachment: '', //附近的集合
        menulist: null,//一级导航
        lnglat: {},//经纬度
        actionUrl: process.env.VUE_APP_BASE_API + "/couplet-admin/file/uploadImage", //上传图片的url
        tokenObj: { "author-token-key": localStorage.getItem("token") },  //上传的请求头token
        token: getToken(),
        routers: constantRoutes,
        addRouters: []
    },
    getters: {
        userId_: state => state.userId,
        mapcontrols_: state => state.mapcontrols,
        carlist_: state => state.carlist,
        attachment_: state => state.attachment,
        menulist_: state => state.menulist,
        lnglat_: state => state.lnglat,
        actionUrl_: state => state.actionUrl,
        tokenObj_: state => state.tokenObj,
        token_: state => state.token,
        routers_: state => state.routers,
        addRouters_: state => state.addRouters
    },
    mutations: {
        changemapcontrols: function (state, payload) {
            state.mapcontrols = payload
        },
        changecarlist: function (state, payload) {
            state.carlist = payload
        },
        changeMenulist: function (state, payload) {
            state.menulist = payload
        },
        changecheckAttachment: function (state, payload) {
            state.attachment = payload
        },
        changelnglat: function (state, payload) {
            state.lnglat = payload
        },
        changecheckUserId: function (state, payload) {
            state.userId = payload
        },
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_ROUTERS: (state, routers) => {
            state.addRouters = deepClone(routers)
            state.routers = deepClone(constantRoutes.concat(routers))
        }
    },
    actions: {
        changeformDatas({ commit }, datatime) {
            return new Promise((resolve, reject) => {
                let time = formatDate(Number(datatime), "yyyy-MM-dd")
                resolve(time)
            })
        },
        login({ commit }, userInfo) {
            const { username, password } = userInfo
            return new Promise((resolve, reject) => {
                login({ username: username.trim(), password: password }).then(response => {
                    commit('SET_TOKEN', response.body)
                    setToken(response.body)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        getInfo({ dispatch, commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(response => {
                    // if (!data) {
                    //     reject('Verification failed, please Login again.')
                    // }
                    // const menus = data.menuCodes
                    commit('changecheckUserId', response.body.userId)
                    var data = response.body
                    console.log('response', data)
                    // localStorage.setItem('MENU_CODE', menus)
                    const menus = ['/equipmentManagement', '/camera']
                    dispatch('GenerateRoutes', menus).then(res => {
                        resolve(data)
                    })
                }).catch(error => {
                    reject(error)
                })
            })
        },
        resetToken({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        },
        GenerateRoutes({ commit }, data) {
            return new Promise(resolve => {
                const accessRouters = filterAsyncRouter(asyncRouterMap, data)
                accessRouters.push({ path: '*', redirect: '/404', hidden: true })
                commit('SET_ROUTERS', accessRouters)
                resolve()
            })
        }
    }
});
export default store

@/utils/auth 中

// import Cookies from 'js-cookie'

const TokenKey = 'Authorization'

export function getToken() {
  // return Cookies.get(TokenKey)
  return localStorage.getItem(TokenKey)
}

export function setToken(token) {
  // return Cookies.set(TokenKey, token)
  return localStorage.setItem(TokenKey, token)
}

export function removeToken() {
  // return Cookies.remove(TokenKey)
  return localStorage.removeItem(TokenKey)
}

export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  for (const keys in source) {
    if (source.hasOwnProperty(keys)) {
      if (source[keys] && typeof source[keys] === 'object') {
        targetObj[keys] = source[keys].constructor === Array ? [] : {}
        targetObj[keys] = deepClone(source[keys])
      } else {
        targetObj[keys] = source[keys]
      }
    }
  }
  return targetObj
}

@/router 中

import Vue from "vue"
import Router from "vue-router"
import store from "./store";

Vue.use(Router)

// console.log("store.getters",store.getters)
// console.log("store.getters.menulist_",store.getters.menulist_)

const notFound = () => import('@/views/404.vue') //404
//登录相关
const login = () => import('@/views/mine/login.vue') //用户登录
const phoneLogin = () => import('@/views/mine/phoneLogin.vue') //手机登录
const retrievePassword = () => import('@/views/mine/retrievePassword.vue') //找回密码
const modifyPassword = () => import('@/views/mine/modifyPassword.vue') //修改密码

const layout = () => import('@/views/layout/index.vue') //导航
const Index = () => import('@/views/index/index.vue') //首页

//管控中心菜单
const mapControls = () => import('@/views/controlsMenu/mapControls/index.vue') //管控地图
const security = () => import('@/views/controlsMenu/security/index.vue') //安防管理
const fire = () => import('@/views/controlsMenu/fire/index.vue') //消防管理
const car = () => import('@/views/controlsMenu/car/index.vue') //车行管理
const lighting = () => import('@/views/controlsMenu/lighting/index.vue') //智慧照明
const checkAttachment = () => import('@/views/controlsMenu/checkAttachment/index.vue') //附近设备

//设备管理菜单
const equipmentManagement = () => import('@/views/equimentMenu/equipmentManagement/index.vue') //设备管理
const camera = () => import('@/views/equimentMenu/camera/index.vue') //摄像头
const wifismoke = () => import('@/views/equimentMenu/wifismoke/index.vue') //路灯控制
const lightAll = () => import('@/views/equimentMenu/lightAll/index.vue') //智慧灯杆
const postScreen = () => import('@/views/equimentMenu/postScreen/index.vue') //发布屏
//告警管理菜单
const alarmManagement = () => import('@/views/alarmMenu/alarmManagement/index.vue') //告警管理
const alarmManagementHoistory = () => import('@/views/alarmMenu/alarmManagementHoistory/index.vue') //告警管理历史

//事件工单菜单
const eventOrder = () => import('@/views/orderMenu/eventOrder/index.vue') //事件工单
const eventOrderHistory = () => import('@/views/orderMenu/eventOrderHistory/index.vue') //事件工单历史

//巡检菜单
const inspectionTrajectory = () => import('@/views/inspectionMenu/inspectionTrajectory/index.vue') //巡检轨迹
const InspectionTask = () => import('@/views/inspectionMenu/InspectionTask/index.vue') //巡检任务单
const InspectionProject = () => import('@/views/inspectionMenu/InspectionProject/index.vue') //巡检项目组
const InspectionConfig = () => import('@/views/inspectionMenu/InspectionConfig/index.vue') //巡检配置

//预案菜单
const emergencyPlan = () => import('@/views/planMenu/emergencyPlan/index.vue') //应急预案

//系统配置菜单
const user = () => import('@/views/systemMenu/user/index.vue') //用户管理
const org = () => import('@/views/systemMenu/org/index.vue') //组织管理
const area = () => import('@/views/systemMenu/area/index.vue') //区域管理
const role = () => import('@/views/systemMenu/role/index.vue') //角色管理
const menu = () => import('@/views/systemMenu/menu/index.vue') //菜单管理
const log = () => import('@/views/systemMenu/log/index.vue') //操作日志
const partition = () => import('@/views/systemMenu/partition/index.vue') //系统项目管理
const dictionary = () => import('@/views/systemMenu/dictionary/index.vue') //数据字典管理
const appPlat = () => import('@/views/systemMenu/platform/appPlat/index.vue') //平台服务管理  -- 应用平台
const provider = () => import('@/views/systemMenu/platform/provider/index.vue') //平台服务管理  -- 供应商平台
const configManage = () => import('@/views/systemMenu/platform/provider/configManage/index.vue') //平台服务管理  -- 供应商平台--园区配置管理
const apiManage = () => import('@/views/systemMenu/platform/provider/apiManage/index.vue') //平台服务管理  -- 供应商平台--接口管理


//-----------------------------
/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export const constantRoutes = [
    { path: "/404", name: '404', component: notFound, hidden: true },
    { path: "/login", name: "login", component: login, hidden: true },
    { path: "/phoneLogin", name: "phoneLogin", component: phoneLogin, hidden: true },
    { path: "/retrievePassword", name: "retrievePassword", component: retrievePassword, hidden: true },
    { path: "/modifyPassword", name: "modifyPassword", component: modifyPassword, hidden: true },
    {
        path: '/',
        component: layout,
        redirect: '/mapControls',
        children: [{
            path: 'mapControls',
            name: 'mapControls',
            component: mapControls,
        },
        ]
    },
]
//动态加载路由
export const asyncRouterMap = [
    {
        path: '/equipmentManagement',
        component: layout,
        meta: { title: 'equipmentManagement', menu_code: '/equipmentManagement' },
        redirect: '/equipmentManagement',
        children: [{
            path: '/equipmentManagement',
            name: 'equipmentManagement',
            component: equipmentManagement,
            meta: { title: 'equipmentManagement', menu_code: '/equipmentManagement' },
            hidden: true
        },
        {
            path: '/camera',
            name: 'camera',
            component: camera,
            meta: { title: 'camera', menu_code: '/camera' },
            hidden: true
        }
        ]
    },
]

const createRouter = () => new Router({
    // mode: 'history', // require service support
    // mode: 'hash', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher // reset router
}

export default router

permission.js 中

import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie

NProgress.configure({ showSpinner: false }) // NProgress Configuration  是否有转圈效果
const whiteList = ['/login'] // 没有重定向白名单

router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start()
  // 确定用户是否已登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录,则重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.userId_;
      if (hasGetUserInfo) {
        // console.log("有用户信息");
        next();
      } else {
        // console.log("没用户信息");
        try {
          // 获得用户信息
          await store.dispatch('getInfo');
          router.addRoutes(store.getters.addRouters_)//动态路由
          next({ ...to })
        } catch (error) {
          // 删除token,进入登录页面重新登录
          await store.dispatch('resetToken');
          Message.error(error || 'Has Error');
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }

    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免费登录白名单,直接去
      next()
    } else {
      // 没有访问权限的其他页面被重定向到登录页面。
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 完成进度条
  NProgress.done()
})

基本剩下的雷同文章来源了

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k