权限管理系统-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 sidebarbreadcrumb: 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 supportscrollBehavior: () => ({ 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 infogetInfo({ commit, state }) {return new Promise((resolve, reject) => {getInfo(state.token).then(response => {const { data } = responseif (!data) {return reject('Verification failed, please Login again.')}const { name, avatar } = datacommit('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 sentif (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修改为tokenconfig.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 = hasBtnPermissionimport 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 titledocument.title = getPageTitle(to.meta.title)// determine whether the user has logged inconst hasToken = getToken()if (hasToken) {if (to.path === '/login') {// if is logged in, redirect to the home pagenext({ path: '/' })NProgress.done()} else {const hasGetUserInfo = store.getters.nameif (hasGetUserInfo) {next()} else {try {// get user infoawait 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-loginconsole.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 directlynext()} 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 barNProgress.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) {debuggerconsole.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.hqwc.cn/news/537329.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Antd中s-table组件某字段进行排序

Antd中s-table组件某字段进行排序 提前说明&#xff0c;s-table组件包含分页等功能 <s-tableref"table":columns"columns":data"loadData"bordered:row-key"(record) > record.id"></s-table>而其中loadData为获取表数…

光电测径仪亦能对透明胶管进行在线测径

关键词&#xff1a;光电测径仪,胶管测径仪,透明胶管测径仪,在线测径 现在各种胶管产品的生产都在使用测径仪进行外径的实时检测与控制&#xff0c;但现在的在线测径仪都是光学检测设备&#xff0c;而透明胶管是透光的&#xff0c;因此很多人会有顾虑&#xff0c;在线测径仪是否…

腾讯云服务器地域选择方法,神仙教程,看这一篇就够了

腾讯云服务器地域怎么选择&#xff1f;不同地域之间有什么区别&#xff1f;腾讯云哪个地域好&#xff1f;地域选择遵循就近原则&#xff0c;访客距离地域越近网络延迟越低&#xff0c;速度越快。腾讯云百科txybk.com告诉大家关于地域的选择还有很多因素&#xff0c;地域节点选择…

26-Java访问者模式 ( Visitor Pattern )

Java访问者模式 摘要实现范例 访问者模式&#xff08;Visitor Pattern&#xff09;使用了一个访问者类&#xff0c;它改变了元素类的执行算法&#xff0c;通过这种方式&#xff0c;元素的执行算法可以随着访问者改变而改变访问者模式中&#xff0c;元素对象已接受访问者对象&a…

聚氨酯封孔剂因为热爱

忙忙碌碌又一天,对每个顾客都用心服务,因为热爱,所以不辛苦,因为热爱,即使无数遍的重复也不会厌倦。 聚氨酯封孔材料的主要性能特点&#xff1a; 1、粘度低&#xff0c;易渗入微小裂隙&#xff1b; 2、粘合能力很强&#xff0c;具有持久强粘结性&#xff1b; 3、柔韧性.越&am…

如何注册Devin-首个全自主AI软件工程师

最近devin大火&#xff0c;具体的就不说了&#xff0c;大家应该都知道&#xff0c;写代码非常nb&#xff0c;这里说一下devin的注册方式&#xff0c;目前devin的内测已经开启。 官网https://www.cognition-labs.com/blog注册网址Your reliable AI software engineerhttps://pr…

机器学习模型—支持向量机 (SVM)

机器学习模型—支持向量机 (SVM) 支持向量机 (SVM) 是一种强大的机器学习算法,用于线性或非线性分类、回归,甚至异常值检测任务。SVM 可用于各种任务,例如文本分类、图像分类、垃圾邮件检测、笔迹识别、基因表达分析、人脸检测和异常检测。SVM 在各种应用中具有适应性和高效…

SpringBoot启动过程

构建SpringApplication对象 这里分为2部分,先new一个SpringApplication对象【入参是启动类】,再去调用这个对象的run方法。 1.primarySources属性记录传进来的启动类是什么,当做spring的配置类 2.有可能不是web应用,也能是Springboot java应用【recative是响应式的 Servle…

如何使用vue定义组件之——父组件调用子组件数据

首先&#xff0c;准备父子容器&#xff1a; <div class"container"><my-father></my-father><my-father></my-father><my-father></my-father><!-- 此处无法调用子组件&#xff0c;子组件必须依赖于父组件进行展示 --&…

【五、接口自动化测试】GET/POST 请求区别

大家好&#xff0c;我是山茶&#xff0c;一个探索AI 测试的程序员 在网上看到了许多关于post与get之间区别的帖子&#xff0c;也有很多帖子是直接粘贴复制的&#xff0c;甚至连标题、符号都没改&#xff0c;甚至还有很多争议 一、post、get 关于post与get之间区别&#xff0c;…

VsCode免密登录

创建本地密匙 按下WinR输入cmd&#xff0c;输入 ssh-keygen -t rsa然后连续回车直到结束 找到Your public key has been saved in C:\Users\Administrator/.ssh/id_rsa.pub&#xff0c;每个人都不一样找到密匙所在地 打开id_rsa.pub这个文件&#xff0c;可以用记事本打开&am…

GPT-4.5 Turbo意外曝光,最快明天发布?OpenAI终于要放大招了!

大家好&#xff0c;我是木易&#xff0c;一个持续关注AI领域的互联网技术产品经理&#xff0c;国内Top2本科&#xff0c;美国Top10 CS研究生&#xff0c;MBA。我坚信AI是普通人变强的“外挂”&#xff0c;所以创建了“AI信息Gap”这个公众号&#xff0c;专注于分享AI全维度知识…