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

来自: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()
})

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

转载于:https://www.cnblogs.com/Byme/p/11497719.html

你可能感兴趣的:(javascript)