权限管理系统-0.4.1

5.4 权限管理前端开发

5.4.1 src/components

新建ParentView文件夹,并在文件夹中新建index.vue文件。
在这里插入图片描述
并在index.vue中加入以下内容:

<template>
  <router-view />
</template>

5.4.2 layout/components/Sidebar/index.vue

    routes() {
      // return this.$router.options.routes
      //新增内容
      return this.$router.options.routes.concat(global.antRouter)
    },

5.4.3 router

在index.js中只留以下内容:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [{
      path: 'dashboard',
      name: 'Dashboard',
      component: () => import('@/views/dashboard/index'),
      meta: { title: 'Dashboard', icon: 'dashboard' }
    }]
  }

  // {
  //   path: '/system',
  //   component: Layout,
  //   meta: {
  //     title: '系统管理',
  //     icon: 'el-icon-s-tools'
  //   },
  //   alwaysShow: true,
  //   children: [
  //     {
  //       name: 'sysUser',
  //       path: 'sysUser',
  //       component: () => import('@/views/system/sysUser/list'),
  //       meta: {
  //         title: '用户管理',
  //         icon: 'el-icon-s-custom'
  //       },
  //     },
  //     {
  //       path: 'sysRole',
  //       component: () => import('@/views/system/sysRole/list'),
  //       meta: {
  //         title: '角色管理',
  //         icon: 'el-icon-s-help'
  //       },
  //     },
  //     {
  //       name: 'sysMenu',
  //       path: 'sysMenu',
  //       component: () => import('@/views/system/sysMenu/list'),
  //       meta: {
  //         title: '菜单管理',
  //         icon: 'el-icon-s-unfold'
  //       },
  //     },
  //     {
  //       path: 'assignAuth',
  //       component: () => import('@/views/system/sysMenu/assignAuth'),
  //       meta: {
  //         activeMenu: '/system/sysRole',
  //         title: '角色授权'
  //       },
  //       hidden: true,
  //     }
  //   ]
  // },

  // {
  //   path: '/form',
  //   component: Layout,
  //   children: [
  //     {
  //       path: 'index',
  //       name: 'Form',
  //       component: () => import('@/views/form/index'),
  //       meta: { title: 'Form', icon: 'form' }
  //     }
  //   ]
  // },

  // {
  //   path: '/nested',
  //   component: Layout,
  //   redirect: '/nested/menu1',
  //   name: 'Nested',
  //   meta: {
  //     title: 'Nested',
  //     icon: 'nested'
  //   },
  //   children: [
  //     {
  //       path: 'menu1',
  //       component: () => import('@/views/nested/menu1/index'), // Parent router-view
  //       name: 'Menu1',
  //       meta: { title: 'Menu1' },
  //       children: [
  //         {
  //           path: 'menu1-1',
  //           component: () => import('@/views/nested/menu1/menu1-1'),
  //           name: 'Menu1-1',
  //           meta: { title: 'Menu1-1' }
  //         },
  //         {
  //           path: 'menu1-2',
  //           component: () => import('@/views/nested/menu1/menu1-2'),
  //           name: 'Menu1-2',
  //           meta: { title: 'Menu1-2' },
  //           children: [
  //             {
  //               path: 'menu1-2-1',
  //               component: () => import('@/views/nested/menu1/menu1-2/menu1-2-1'),
  //               name: 'Menu1-2-1',
  //               meta: { title: 'Menu1-2-1' }
  //             },
  //             {
  //               path: 'menu1-2-2',
  //               component: () => import('@/views/nested/menu1/menu1-2/menu1-2-2'),
  //               name: 'Menu1-2-2',
  //               meta: { title: 'Menu1-2-2' }
  //             }
  //           ]
  //         },
  //         {
  //           path: 'menu1-3',
  //           component: () => import('@/views/nested/menu1/menu1-3'),
  //           name: 'Menu1-3',
  //           meta: { title: 'Menu1-3' }
  //         }
  //       ]
  //     },
  //     {
  //       path: 'menu2',
  //       component: () => import('@/views/nested/menu2/index'),
  //       name: 'Menu2',
  //       meta: { title: 'menu2' }
  //     }
  //   ]
  // },

  // {
  //   path: 'external-link',
  //   component: Layout,
  //   children: [
  //     {
  //       path: 'https://panjiachen.github.io/vue-element-admin-site/#/',
  //       meta: { title: 'External Link', icon: 'link' }
  //     }
  //   ]
  // },

  // // 404 page must be placed at the end !!!
  // { path: '*', redirect: '/404', hidden: true }
]

const createRouter = () => new Router({
  // mode: 'history', // 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

新建_import_development.js 和_import_production.js 两个文件。

//_import_development.js
module.exports = file => require('@/views/' + file + '.vue').default

//_import_production.js
module.exports = file => () => import('@/views/' + file + '.vue')

5.4.4 store/modules/user.js

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',

    buttons: [],//新增
    menus: ''//新增
  }
}
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },

//新增
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons
  },
  //新增
  SET_MENUS: (state, menus) => {
    state.menus = menus
  }
}
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)

		//新增
        commit('SET_BUTTONS', data.buttons)
        //新增
        commit('SET_MENUS', data.routers)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

5.4.5 store/getter.js

const getters = {
  sidebar: state => state.app.sidebar,
  device: state => state.app.device,
  token: state => state.user.token,
  avatar: state => state.user.avatar,
  name: state => state.user.name,

  //新增
  buttons: state => state.user.buttons,
  //新增
  menus: state => state.user.menus
}
export default getters

5.4.6 utils

在utils中新建文件夹btn-permission.js。

//btn-permission.js
import store from '@/store'

/**
 * 判断当前用户是否有此按钮权限
 * 按钮权限字符串 permission
 */
export default function hasBtnPermission(permission) {
  // 得到当前用户的所有按钮权限
  const myBtns = store.getters.buttons
  // 如果指定的功能权限在myBtns中, 返回true ==> 这个按钮就会显示, 否则隐藏
  return myBtns.indexOf(permission) !== -1
}

修改request.js:

  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation

	  //将x-token修改为token
      config.headers['token'] = getToken()
    }
    return config
  },

5.4.7 views/login/index.vue

用户名和密码只检查长度:

    const validateUsername = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }

5.4.8 main.js

// 新增
import hasBtnPermission from '@/utils/btn-permission'
Vue.prototype.$hasBP = hasBtnPermission

import formCreate from '@form-create/element-ui'
import FcDesigner from '@form-create/designer'
Vue.use(formCreate)
Vue.use(FcDesigner)

5.4.9 permission.js

替换为下面的内容:

import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 水平进度条提示: 在跳转路由时使用
import 'nprogress/nprogress.css' // 水平进度条样式
import getPageTitle from '@/utils/get-page-title' // 获取应用头部标题的函数
import Layout from '@/layout'
import ParentView from '@/components/ParentView'
const _import = require('./router/_import_' + process.env.NODE_ENV) // 获取组件的方法

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login'] // no redirect whitelist
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')// 请求获取用户信息
          if (store.getters.menus.length < 1) {
            global.antRouter = []
            next()
          }
          const menus = filterAsyncRouter(store.getters.menus)// 1.过滤路由
          console.log(menus)
          router.addRoutes(menus) // 2.动态添加路由
          const lastRou = [{ path: '*', redirect: '/404', hidden: true }]
          router.addRoutes(lastRou)
          global.antRouter = menus // 3.将路由数据传递给全局变量,做侧边栏菜单渲染工作
          next({
            ...to,
            replace: true
          })
          // next()
        } catch (error) {
          // remove token and go to login page to re-login
          console.log(error)
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else { /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => { // finish progress bar
  NProgress.done()
}) // // 遍历后台传来的路由字符串,转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        try {
          route.component = _import(route.component)// 导入组件
        } catch (error) {
          debugger
          console.log(error)
          route.component = _import('dashboard/index')// 导入组件
        }
      }
    }
    if (route.children && route.children.length > 0) {
      route.children = filterAsyncRouter(route.children)
    } else {
      delete route.children
    }
    return true
  })
  return accessedRouters
}

5.4.10 按钮权限控制

在写按钮时按照如下写法即可:

<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)" title="删除" :disable="$hasBP('bnt.sysUser.remove')===false"/>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/456458.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

潜水耳机哪个牌子好?潜水党必看的游泳耳机专业性能详解!

在游泳、潜水等水上活动中&#xff0c;一个好的耳机可以让你更加享受水中的乐趣。而随着科技的不断发展&#xff0c;市面上涌现了越来越多的游泳耳机品牌和型号&#xff0c;让人眼花缭乱。 &#xff08;以下是之前测试过的游泳耳机&#xff1a;&#xff09; 那么&#xff0c;潜…

从零开始搭建医保购药APP:技术选择与开发流程

医保购药APP作为一种创新的医疗服务工具&#xff0c;为用户提供了便捷的医保购药流程&#xff0c;同时也为医疗机构提供了更高效的管理和服务方式。今天小编将为大家讲解如何从零开始搭建一款医保购药APP&#xff0c;包括技术选择和开发流程。 一、技术选择 在搭建医保购药APP…

python面向对象的三大特性:封装,继承,多态

1、面向对象有哪些特性 三种&#xff1a;封装性、继承性、多态性 2、Python中的封装 在Python代码中&#xff0c;封装有两层含义&#xff1a; ① 把现实世界中的主体中的属性和方法书写到类的里面的操作即为封装 ② 封装可以为属性和方法添加为私有权限&#xff0c;不能直…

【C++练级之路】【Lv.13】多态(你真的了解虚函数和虚函数表吗?)

快乐的流畅&#xff1a;个人主页 个人专栏&#xff1a;《C语言》《数据结构世界》《进击的C》 远方有一堆篝火&#xff0c;在为久候之人燃烧&#xff01; 文章目录 一、虚函数与重写1.1 虚函数1.2 虚函数的重写1.3 重写的特例1.4 final和override&#xff08;C11&#xff09;1.…

【ROS+amcl+Movebase】多机器人导航

学过单机器人在已知地图中的导航后&#xff0c;想到如果有多个机器人在同一地图如何导航&#xff0c;于是在网上学习了下&#xff0c;主流方案即在单机器人导航的基础上引入命名空间。 参考文章1 参考文章2 参考文章3 一、实验环境 Ubuntu1804&#xff08;虚拟机&#xff09;…

VSCode+python单步调试库代码

VSCodepython单步调试库代码 随着VSCode版本迭代更新&#xff0c;在最新的1.87.x中&#xff0c;使用Python Debugger扩展进行调试时&#xff0c;扩展的justMyCode默认属性为true&#xff0c;不会进入库中的代码。这对debug而言不太方便&#xff0c;因此需要手动设置一下&#…

在vite(vue)项目中使用mockjs

在vite&#xff08;vue&#xff09;项目中使用mockjs 在开发环境使用 1、首先创建vite项目 yarn create vite选择vue&#xff0c;选择默认的js版本 2、进入项目文件夹中执行yarn安装依赖 yarn add axios mockjs vite-plugin-mock3、安装axios、mockjs及插件 yarn add axio…

【方法封装】时间格式化输出,获取请求设备和IP

目录 时间类 1.1 获取当前时间&#xff0c;以特定格式化形式输出 1.2 自定义时间&#xff0c;以特定格式化输出 1.3 获取当前时间&#xff0c;自定义格式化 1.4 自定义时间&#xff0c;自定义格式化 设备类 根据请求头信息&#xff0c;获取用户发起请求的设备 请求IP类 …

vue3中的文字滚动播报

vue3中的文字滚动播报 之前UI框架一直使用的elementPlus&#xff0c;有个需求&#xff0c;需要在页面上写个滚动播放新闻的功能&#xff0c;发现UI框架居然没有这个组件。花了一下午&#xff0c;在ChatGPT的帮助下&#xff0c;总算写成功了&#xff0c;先看最终展示效果 web页…

Python打印输出Linux中最常用的linux命令之示例

一、Linux中的~/.bash_history文件说明&#xff1a; 该文件保存了linux系统中运行过的命令的历史。使用该文件来获取命令的列表&#xff0c;并统计命令的执行次数。统计时&#xff0c;只统计命令的名称&#xff0c;以不同参数调用相同的命令也视为同一命令。 二、示例代码&am…

npm yarn 一起使用报错

项目记录&#xff0c;具有独特性&#xff0c;仅供参考 项目好好的运行&#xff0c;前一天装个测试工具包&#xff0c; 突然就不行了&#xff0c;卸载重装也不行&#xff0c;所有的项目都安装失败&#xff0c;新起一个项目也不行&#xff0c;有时候某个单独安装一个包可以&…

【爬虫】requests.post请求中的data和json使用区别

请求体是键值对形式&#xff08;无花括号&#xff09;&#xff0c;请求时需要使用data参数处理。 代码&#xff1a; data {...} ret requests.post(url, headersheaders, datadata)请求体是字典形式&#xff08;有花括号&#xff09;&#xff0c;请求时需要使用json参数处理。…

GPT-5:人工智能的下一个前沿即将到来

当我们站在人工智能新时代的门槛上时&#xff0c;GPT-5即将到来的呼声愈发高涨且迫切。作为革命性的GPT-3的继任者&#xff0c;GPT-5承诺将在人工智能领域迈出量子跃迁式的进步&#xff0c;其能力可能重新定义我们与技术的互动方式。 通往GPT-5之路 通往GPT-5的旅程已经标记着…

Markdown编辑器VNote突然让我不知所措 编辑区变小问题

环境&#xff1a;macOS VNote 3.16.0 一直喜欢用VNote因为它的编辑和显示的切换分离及右边的大纲&#xff08;菜单&#xff09;比CSDN在上方的大纲好用很多&#xff01; 但今天在编辑时不知碰到了什么键&#xff0c;编辑界面变成了下面的样子 按了回撤也没有反应&#xff0c…

mineadmin 快速安装部署(docker环境)

前提条件&#xff1a;已安装docker 一、下载dnmp环境包 github地址&#xff1a;https://github.com/tomorrow-sky/dnmp gitee地址&#xff1a; https://gitee.com/chenjianchuan/dnmp 二、看一下dnmp包目录结构 三、打开docker-compose.yml 文件&#xff0c;将不需要…

鸿蒙Harmony应用开发—ArkTS声明式开发(基础手势:Web)上篇

提供具有网页显示能力的Web组件&#xff0c;ohos.web.webview提供web控制能力。 说明&#xff1a; 该组件从API Version 8开始支持。后续版本如有新增内容&#xff0c;则采用上角标单独标记该内容的起始版本。示例效果请以真机运行为准&#xff0c;当前IDE预览器不支持。 需要权…

联想小新电脑出现蓝屏问题解决(通过系统重置解决了)

只看问题描述和文章最后一行字即可 问题描述 电脑出现蓝屏&#xff0c;如下 尝试解决&#xff08;并未解决&#xff09; 搜索FAULTY_HARDWARE_CORRUPTED_PAGE寻找解决方案&#xff0c;找到较为靠谱的文章&#xff1a;记录蓝屏问题FAULTY_HARDWARE_CORRUPTED_PAGE 根据文章提…

深入探讨`g++`与`gcc`:混合编程中的编译链接艺术

深入探讨g与gcc&#xff1a;混合编程中的编译链接艺术 在混合使用C和C进行项目开发时&#xff0c;选择正确的编译器和链接器对项目的成功至关重要。虽然gcc和g都是GNU编译器集合&#xff08;GCC&#xff09;的重要组成部分&#xff0c;它们在处理混合语言项目时展现出了不同的能…

【LeetCode每日一题】2864. 最大二进制奇数

文章目录 [2864. 最大二进制奇数](https://leetcode.cn/problems/maximum-odd-binary-number/)思路&#xff1a;代码1&#xff1a; 2864. 最大二进制奇数 思路&#xff1a; 1.拼贴字符串。 2.遍历字符串s,统计1的个数。 3.如果只有一个1&#xff0c;将1放在末尾&#xff0c;…

AI实战:借助Python与PaddleOCR,实现高精度文本检测与识别

1、引言 欢迎来到今天的教程&#xff1a;“驾驭PaddleOCR&#xff0c;解锁Python文字识别新技能”。在本篇文章中&#xff0c;我们将手把手教你如何安装及使用这款强大的Python库&#xff0c;轻松应对各类图像中的文字识别问题。 2、安装PaddleOCR 首先确保你的环境中已安装…
最新文章