elementuiadmin去掉默认mock权限控制的设置
一般前后端分离的项目,前端都很少通过mock模拟数据来调用测试,因为后期api出来后,可能还得修改结构,颇为麻烦。
本文从实践中总结,完全去掉默认的mock控制。
1.找到vue.config.js文件,去掉mock的加载
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
}
// before: require('./mock/mock-server.js') // 注释掉这一行
}
2.找到main.js,注释掉相关mock
// if (process.env.NODE_ENV === 'production') {
// const { mockXHR } = require('../mock')
// mockXHR()
// }
3.login.vue登录页面,直接调用api/user.js下的方法。
先引用login和reg进来,否则用默认的登录接口会再调用用户详情接口
import { login, reg } from '@/api/user'
把原来的登录方法注释掉,直接调用成功后,把登录token值set到js-cookie里
handleLogin() {
this.$refs.loginForm.validate(valid => {
if (valid) {
this.loading = true
login(this.loginForm).then((res) => {
if (res && res.code === 0 && res.data && res.data.token) {
setToken(res.data.token)
this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
this.loading = false
}
}).catch(() => {
this.loading = false
})
// this.$store.dispatch('user/login', this.loginForm)
// .then(() => {
// this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
// this.loading = false
// })
// .catch(() => {
// this.loading = false
// })
} else {
console.log('error submit!!')
return false
}
})
},
4.登录后就是菜单的展示问题了,找到/layout/components/Sidebar/index.vue文件,去掉权限控制permission_routes参数,改为:
<sidebar-item v-for="route in getRouterList" :key="route.path" :item="route" :base-path="route.path" />
import routesArr from '@/router/index'
export default {
components: { SidebarItem, Logo, routesArr },
computed: {
getRouterList() {
return routesArr.options.routes
},
...mapGetters([
// 'permission_routes', // 注释掉
'sidebar'
]),
OK!完美!
vue-elementui-admin的动态权限控制
最近打算仔细的学习一下vue-elemnetui-admin的代码,一是工作需要用到,需要加工一些东西,还有一个就是打算之后好好学习vue,看看源码啥的,所以先从这个框架学起来。
都是一些自己的学习笔记,做一些记录,有不对的地方恳请大家指出,可以一起讨论。
学习了一下permission文件夹下的role.js,用来控制不同用户能够查看菜单的权限
<template>
<div class="app-container">
<el-button type="primary" @click="handleAddRole">New Role</el-button>
<el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
<el-table-column align="center" label="Role Key" width="220">
<template slot-scope="scope">
{{ scope.row.key }}
</template>
</el-table-column>
<el-table-column align="center" label="Role Name" width="220">
<template slot-scope="scope">
{{ scope.row.name }}
</template>
</el-table-column>
<el-table-column align="header-center" label="Description">
<template slot-scope="scope">
{{ scope.row.description }}
</template>
</el-table-column>
<el-table-column align="center" label="Operations">
<template slot-scope="scope">
<el-button type="primary" size="small" @click="handleEdit(scope)">Edit</el-button>
<el-button type="danger" size="small" @click="handleDelete(scope)">Delete</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit Role':'New Role'">
<el-form :model="role" label-width="80px" label-position="left">
<el-form-item label="Name">
<el-input v-model="role.name" placeholder="Role Name" />
</el-form-item>
<el-form-item label="Desc">
<el-input
v-model="role.description"
:autosize="{ minRows: 2, maxRows: 4}"
type="textarea"
placeholder="Role Description"
/>
</el-form-item>
<el-form-item label="Menus">
<el-tree
ref="tree"
:check-strictly="checkStrictly"
:data="routesData"
:props="defaultProps"
show-checkbox
node-key="path"
class="permission-tree"
/>
</el-form-item>
</el-form>
<div style="text-align:right;">
<el-button type="danger" @click="dialogVisible=false">Cancel</el-button>
<el-button type="primary" @click="confirmRole">Confirm</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import path from 'path'
import { deepClone } from '@/utils'
import { getRoutes, getRoles, addRole, deleteRole, updateRole } from '@/api/role'
const defaultRole = {
key: '',
name: '',
description: '',
routes: []
}
export default {
data() {
return {
role: Object.assign({}, defaultRole),
routes: [], // 路由列表
rolesList: [], // 角色列表以及对应的路由信息
dialogVisible: false,
dialogType: 'new',
checkStrictly: false,
defaultProps: {
children: 'children',
label: 'title'
}
}
},
computed: {
routesData() {
return this.routes
}
},
created() {
// Mock: get all routes and roles list from server
this.getRoutes() // 获取全部的路由列表
this.getRoles() // 获取全部角色加里面的权限路由
},
methods: {
async getRoutes() {
const res = await getRoutes() // res是全部路由列表,由constantRoutes静态路由和asyncRoutes动态路由拼接组成
this.serviceRoutes = res.data // 将全部路由列表赋值给serviceRoutes
this.routes = this.generateRoutes(res.data) // 生成树的数据
},
async getRoles() {
const res = await getRoles() // 获取全部的角色信息,以及角色对应的路由信息
this.rolesList = res.data // 拿到表格数据
},
// Reshape the routes structure so that it looks the same as the sidebar
// 产生最终路由的方法,参数是全部路由信息和‘/'
generateRoutes(routes, basePath = '/') {
const res = []
for (let route of routes) { // 遍历所有路由信息
// skip some route
if (route.hidden) { continue } // hidden属性为true,则继续
const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route) // 得到子路由的完整信息
// console.log('onlyOneShowingChild', onlyOneShowingChild)
// 有二级菜单的路由返回的false,进行递归
// 你可以设置 alwaysShow: true,这样它就会忽略之前定义的规则,一直显示根路由
// 如果有chilren和生成的信息且不是跟路由
if (route.children && onlyOneShowingChild && !route.alwaysShow) {
route = onlyOneShowingChild
}
const data = {
path: path.resolve(basePath, route.path),
title: route.meta && route.meta.title
}
// recursive child routes
if (route.children) { // 递归路由的子路由
data.children = this.generateRoutes(route.children, data.path)
}
res.push(data) // 放进res中生成路由
}
return res
},
// 把树的数据routes放进数组里
generateArr(routes) {
let data = []
routes.forEach(route => {
data.push(route)
if (route.children) {
const temp = this.generateArr(route.children)
if (temp.length > 0) {
data = [...data, ...temp]
}
}
})
return data
},
handleAddRole() {
this.role = Object.assign({}, defaultRole)
if (this.$refs.tree) {
this.$refs.tree.setCheckedNodes([])
}
this.dialogType = 'new'
this.dialogVisible = true
},
// 显示该角色的菜单信息
handleEdit(scope) {
this.dialogType = 'edit' // 修改角色权限菜单
this.dialogVisible = true
this.checkStrictly = true
this.role = deepClone(scope.row) // 深度克隆该行的信息,包括路由信息
console.log('role',this.role)
this.$nextTick(() => {
const routes = this.generateRoutes(this.role.routes) // 产生该角色所能查看到的路由信息
// 设置点开该角色能看到的菜单已被选中,this.generateArr(routes)接收勾选节点数据的数组,
this.$refs.tree.setCheckedNodes(this.generateArr(routes))
// set checked state of a node not affects its father and child nodes
this.checkStrictly = false
// 在显示复选框的情况下,是否严格的遵循父子不互相关联的做法
})
},
handleDelete({ $index, row }) {
this.$confirm('Confirm to remove the role?', 'Warning', {
confirmButtonText: 'Confirm',
cancelButtonText: 'Cancel',
type: 'warning'
})
.then(async() => {
await deleteRole(row.key)
this.rolesList.splice($index, 1)
this.$message({
type: 'success',
message: 'Delete succed!'
})
})
.catch(err => { console.error(err) })
},
// 生成勾选完的路由结构
generateTree(routes, basePath = '/', checkedKeys) {
const res = []
for (const route of routes) { // 生成每个路由的绝对路径
const routePath = path.resolve(basePath, route.path)
// recursive child routes
if (route.children) { // 递归children
route.children = this.generateTree(route.children, routePath, checkedKeys)
}
// 如果勾选结果的路径包含有遍历全部路由的当前路由,或该路由没有子路由,把该路由放置
if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
res.push(route)
}
}
return res
},
async confirmRole() {
const isEdit = this.dialogType === 'edit'
const checkedKeys = this.$refs.tree.getCheckedKeys() // 选中的所有节点的keys生成数组
console.log('checkedKeys', checkedKeys)
// 深度克隆全部路由列表,将勾选完的路由和全部路由对比,生成勾选完的完整路由结构
this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)
// 如果是修改角色权限菜单
if (isEdit) {
await updateRole(this.role.key, this.role) // 调接口更新该角色菜单权限
for (let index = 0; index < this.rolesList.length; index++) {
if (this.rolesList[index].key === this.role.key) {
this.rolesList.splice(index, 1, Object.assign({}, this.role))
break
}
}
} else { // 如果不是编辑状态,就是新增角色信息,调接口新增角色
const { data } = await addRole(this.role)
this.role.key = data.key
this.rolesList.push(this.role)
}
const { description, key, name } = this.role
this.dialogVisible = false
this.$notify({ // 提示信息
title: 'Success',
dangerouslyUseHTMLString: true,
message: `
<div>Role Key: ${key}</div>
<div>Role Name: ${name}</div>
<div>Description: ${description}</div>
`,
type: 'success'
})
},
// reference: src/view/layout/components/Sidebar/SidebarItem.vue
onlyOneShowingChild(children = [], parent) { // 参数是子路由。父路由
let onlyOneChild = null
const showingChildren = children.filter(item => !item.hidden) // 拿到子路由中children中不是hidden的路由展示
// 当只有一条子路由时,该子路由就是自己
// When there is only one child route, the child route is displayed by default
if (showingChildren.length === 1) {
// path.resolve()方法可以将多个路径解析为一个规范化的绝对路径,parent.path为根路径,onlyOneChild.path为拼接路径
onlyOneChild = showingChildren[0]
onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
// 返回子路由的完整路由信息
return onlyOneChild
}
// 如果没有要显示的子路由,则显示父路由
// Show parent if there are no child route to display
if (showingChildren.length === 0) {
onlyOneChild = { ... parent, path: '', noShowingChildren: true }
return onlyOneChild
}
return false
}
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。