使用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.  
  3. import routesArr from ‘@/router/index’
  4. export default {
  5.      components: { SidebarItem, Logo, routesArr },
  6.      computed: {
  7.      getRouterList() {
  8.      return routesArr.options.routes
  9.      },
  10.      …mapGetters([
  11.      // ‘permission_routes’, // 注释掉
  12.      ‘sidebar’
  13.      ]),

OK!完美!

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

标签

发表评论