怎么使用elementuiadmin去掉默认mock权限控制的设置

其他教程   发布日期:2025年04月08日   浏览次数:107

本文小编为大家详细介绍“怎么使用elementuiadmin去掉默认mock权限控制的设置”,内容详细,步骤清晰,细节处理妥当,希望这篇“怎么使用elementuiadmin去掉默认mock权限控制的设置”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

elementuiadmin去掉默认mock权限控制的设置

一般前后端分离的项目,前端都很少通过mock模拟数据来调用测试,因为后期api出来后,可能还得修改结构,颇为麻烦。

本文从实践中总结,完全去掉默认的mock控制。

1.找到vue.config.js文件,去掉mock的加载

  1. devServer: {
  2. port: port,
  3. open: true,
  4. overlay: {
  5. warnings: false,
  6. errors: true
  7. }
  8. // before: require('./mock/mock-server.js') // 注释掉这一行
  9. }

2.找到main.js,注释掉相关mock

  1. // if (process.env.NODE_ENV === 'production') {
  2. // const { mockXHR } = require('../mock')
  3. // mockXHR()
  4. // }

3.login.vue登录页面,直接调用api/user.js下的方法。

先引用login和reg进来,否则用默认的登录接口会再调用用户详情接口

  1. import { login, reg } from '@/api/user'

把原来的登录方法注释掉,直接调用成功后,把登录token值set到js-cookie里

  1. handleLogin() {
  2. this.$refs.loginForm.validate(valid => {
  3. if (valid) {
  4. this.loading = true
  5. login(this.loginForm).then((res) => {
  6. if (res && res.code === 0 && res.data && res.data.token) {
  7. setToken(res.data.token)
  8. this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
  9. this.loading = false
  10. }
  11. }).catch(() => {
  12. this.loading = false
  13. })
  14. // this.$store.dispatch('user/login', this.loginForm)
  15. // .then(() => {
  16. // this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
  17. // this.loading = false
  18. // })
  19. // .catch(() => {
  20. // this.loading = false
  21. // })
  22. } else {
  23. console.log('error submit!!')
  24. return false
  25. }
  26. })
  27. },

4.登录后就是菜单的展示问题了,找到/layout/components/Sidebar/index.vue文件,去掉权限控制permission_routes参数,改为:

  1. <sidebar-item v-for="route in getRouterList" :key="route.path" :item="route" :base-path="route.path" />
  2. import routesArr from '@/router/index'
  3. export default {
  4. components: { SidebarItem, Logo, routesArr },
  5. computed: {
  6. getRouterList() {
  7. return routesArr.options.routes
  8. },
  9. ...mapGetters([
  10. // 'permission_routes', // 注释掉
  11. 'sidebar'
  12. ]),

vue-elementui-admin的动态权限控制

最近打算仔细的学习一下vue-elemnetui-admin的代码,一是工作需要用到,需要加工一些东西,还有一个就是打算之后好好学习vue,看看源码啥的,所以先从这个框架学起来。

都是一些自己的学习笔记,做一些记录,有不对的地方恳请大家指出,可以一起讨论。

学习了一下permission文件夹下的role.js,用来控制不同用户能够查看菜单的权限

  1. <template>
  2. <div class="app-container">
  3. <el-button type="primary" @click="handleAddRole">New Role</el-button>
  4. <el-table :data="rolesList" border>
  5. <el-table-column align="center" label="Role Key" width="220">
  6. <template slot-scope="scope">
  7. {{ scope.row.key }}
  8. </template>
  9. </el-table-column>
  10. <el-table-column align="center" label="Role Name" width="220">
  11. <template slot-scope="scope">
  12. {{ scope.row.name }}
  13. </template>
  14. </el-table-column>
  15. <el-table-column align="header-center" label="Description">
  16. <template slot-scope="scope">
  17. {{ scope.row.description }}
  18. </template>
  19. </el-table-column>
  20. <el-table-column align="center" label="Operations">
  21. <template slot-scope="scope">
  22. <el-button type="primary" size="small" @click="handleEdit(scope)">Edit</el-button>
  23. <el-button type="danger" size="small" @click="handleDelete(scope)">Delete</el-button>
  24. </template>
  25. </el-table-column>
  26. </el-table>
  27. <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit Role':'New Role'">
  28. <el-form :model="role" label-width="80px" label-position="left">
  29. <el-form-item label="Name">
  30. <el-input v-model="role.name" placeholder="Role Name" />
  31. </el-form-item>
  32. <el-form-item label="Desc">
  33. <el-input
  34. v-model="role.description"
  35. :autosize="{ minRows: 2, maxRows: 4}"
  36. type="textarea"
  37. placeholder="Role Description"
  38. />
  39. </el-form-item>
  40. <el-form-item label="Menus">
  41. <el-tree
  42. ref="tree"
  43. :check-strictly="checkStrictly"
  44. :data="routesData"
  45. :props="defaultProps"
  46. show-checkbox
  47. node-key="path"
  48. class="permission-tree"
  49. />
  50. </el-form-item>
  51. </el-form>
  52. <div >
  53. <el-button type="danger" @click="dialogVisible=false">Cancel</el-button>
  54. <el-button type="primary" @click="confirmRole">Confirm</el-button>
  55. </div>
  56. </el-dialog>
  57. </div>
  58. </template>
  59. <script>
  60. import path from 'path'
  61. import { deepClone } from '@/utils'
  62. import { getRoutes, getRoles, addRole, deleteRole, updateRole } from '@/api/role'
  63. const defaultRole = {
  64. key: '',
  65. name: '',
  66. description: '',
  67. routes: []
  68. }
  69. export default {
  70. data() {
  71. return {
  72. role: Object.assign({}, defaultRole),
  73. routes: [], // 路由列表
  74. rolesList: [], // 角色列表以及对应的路由信息
  75. dialogVisible: false,
  76. dialogType: 'new',
  77. checkStrictly: false,
  78. defaultProps: {
  79. children: 'children',
  80. label: 'title'
  81. }
  82. }
  83. },
  84. computed: {
  85. routesData() {
  86. return this.routes
  87. }
  88. },
  89. created() {
  90. // Mock: get all routes and roles list from server
  91. this.getRoutes() // 获取全部的路由列表
  92. this.getRoles() // 获取全部角色加里面的权限路由
  93. },
  94. methods: {
  95. async getRoutes() {
  96. const res = await getRoutes() // res是全部路由列表,由constantRoutes静态路由和asyncRoutes动态路由拼接组成
  97. this.serviceRoutes = res.data // 将全部路由列表赋值给serviceRoutes
  98. this.routes = this.generateRoutes(res.data) // 生成树的数据
  99. },
  100. async getRoles() {
  101. const res = await getRoles() // 获取全部的角色信息,以及角色对应的路由信息
  102. this.rolesList = res.data // 拿到表格数据
  103. },
  104. // Reshape the routes structure so that it looks the same as the sidebar
  105. // 产生最终路由的方法,参数是全部路由信息和‘/'
  106. generateRoutes(routes, basePath = '/') {
  107. const res = []
  108. for (let route of routes) { // 遍历所有路由信息
  109. // skip some route
  110. if (route.hidden) { continue } // hidden属性为true,则继续
  111. const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route) // 得到子路由的完整信息
  112. // console.log('onlyOneShowingChild', onlyOneShowingChild)
  113. // 有二级菜单的路由返回的false,进行递归
  114. // 你可以设置 alwaysShow: true,这样它就会忽略之前定义的规则,一直显示根路由
  115. // 如果有chilren和生成的信息且不是跟路由
  116. if (route.children && onlyOneShowingChild && !route.alwaysShow) {
  117. route = onlyOneShowingChild
  118. }
  119. const data = {
  120. path: path.resolve(basePath, route.path),
  121. title: route.meta && route.meta.title
  122. }
  123. // recursive child routes
  124. if (route.children) { // 递归路由的子路由
  125. data.children = this.generateRoutes(route.children, data.path)
  126. }
  127. res.push(data) // 放进res中生成路由
  128. }
  129. return res
  130. },
  131. // 把树的数据routes放进数组里
  132. generateArr(routes) {
  133. let data = []
  134. routes.forEach(route => {
  135. data.push(route)
  136. if (route.children) {
  137. const temp = this.generateArr(route.children)
  138. if (temp.length > 0) {
  139. data = [...data, ...temp]
  140. }
  141. }
  142. })
  143. return data
  144. },
  145. handleAddRole() {
  146. this.role = Object.assign({}, defaultRole)
  147. if (this.$refs.tree) {
  148. this.$refs.tree.setCheckedNodes([])
  149. }
  150. this.dialogType = 'new'
  151. this.dialogVisible = true
  152. },
  153. // 显示该角色的菜单信息
  154. handleEdit(scope) {
  155. this.dialogType = 'edit' // 修改角色权限菜单
  156. this.dialogVisible = true
  157. this.checkStrictly = true
  158. this.role = deepClone(scope.row) // 深度克隆该行的信息,包括路由信息
  159. console.log('role',this.role)
  160. this.$nextTick(() => {
  161. const routes = this.generateRoutes(this.role.routes) // 产生该角色所能查看到的路由信息
  162. // 设置点开该角色能看到的菜单已被选中,this.generateArr(routes)接收勾选节点数据的数组,
  163. this.$refs.tree.setCheckedNodes(this.generateArr(routes))
  164. // set checked state of a node not affects its father and child nodes
  165. this.checkStrictly = false
  166. // 在显示复选框的情况下,是否严格的遵循父子不互相关联的做法
  167. })
  168. },
  169. handleDelete({ $index, row }) {
  170. this.$confirm('Confirm to remove the role?', 'Warning', {
  171. confirmButtonText: 'Confirm',
  172. cancelButtonText: 'Cancel',
  173. type: 'warning'
  174. })
  175. .then(async() => {
  176. await deleteRole(row.key)
  177. this.rolesList.splice($index, 1)
  178. this.$message({
  179. type: 'success',
  180. message: 'Delete succed!'
  181. })
  182. })
  183. .catch(err => { console.error(err) })
  184. },
  185. // 生成勾选完的路由结构
  186. generateTree(routes, basePath = '/', checkedKeys) {
  187. const res = []
  188. for (const route of routes) { // 生成每个路由的绝对路径
  189. const routePath = path.resolve(basePath, route.path)
  190. // recursive child routes
  191. if (route.children) { // 递归children
  192. route.children = this.generateTree(route.children, routePath, checkedKeys)
  193. }
  194. // 如果勾选结果的路径包含有遍历全部路由的当前路由,或该路由没有子路由,把该路由放置
  195. if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
  196. res.push(route)
  197. }
  198. }
  199. return res
  200. },
  201. async confirmRole() {
  202. const isEdit = this.dialogType === 'edit'
  203. const checkedKeys = this.$refs.tree.getCheckedKeys() // 选中的所有节点的keys生成数组
  204. console.log('checkedKeys', checkedKeys)
  205. // 深度克隆全部路由列表,将勾选完的路由和全部路由对比,生成勾选完的完整路由结构
  206. this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)
  207. // 如果是修改角色权限菜单
  208. if (isEdit) {
  209. await updateRole(this.role.key, this.role) // 调接口更新该角色菜单权限
  210. for (let index = 0; index < this.rolesList.length; index++) {
  211. if (this.rolesList[index].key === this.role.key) {
  212. this.rolesList.splice(index, 1, Object.assign({}, this.role))
  213. break
  214. }
  215. }
  216. } else { // 如果不是编辑状态,就是新增角色信息,调接口新增角色
  217. const { data } = await addRole(this.role)
  218. this.role.key = data.key
  219. this.rolesList.push(this.role)
  220. }
  221. const { description, key, name } = this.role
  222. this.dialogVisible = false
  223. this.$notify({ // 提示信息
  224. title: 'Success',
  225. dangerouslyUseHTMLString: true,
  226. message: `
  227. <div>Role Key: ${key}</div>
  228. <div>Role Name: ${name}</div>
  229. <div>Description: ${description}</div>
  230. `,
  231. type: 'success'
  232. })
  233. },
  234. // reference: src/view/layout/components/Sidebar/SidebarItem.vue
  235. onlyOneShowingChild(children = [], parent) { // 参数是子路由。父路由
  236. let onlyOneChild = null
  237. const showingChildren = children.filter(item => !item.hidden) // 拿到子路由中children中不是hidden的路由展示
  238. // 当只有一条子路由时,该子路由就是自己
  239. // When there is only one child route, the child route is displayed by default
  240. if (showingChildren.length === 1) {
  241. // path.resolve()方法可以将多个路径解析为一个规范化的绝对路径,parent.path为根路径,onlyOneChild.path为拼接路径
  242. onlyOneChild = showingChildren[0]
  243. onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
  244. // 返回子路由的完整路由信息
  245. return onlyOneChild
  246. }
  247. // 如果没有要显示的子路由,则显示父路由
  248. // Show parent if there are no child route to display
  249. if (showingChildren.length === 0) {
  250. onlyOneChild = { ... parent, path: '', noShowingChildren: true }
  251. return onlyOneChild
  252. }
  253. return false
  254. }
  255. }
  256. }

以上就是怎么使用elementuiadmin去掉默认mock权限控制的设置的详细内容,更多关于怎么使用elementuiadmin去掉默认mock权限控制的设置的资料请关注九品源码其它相关文章!